Last active
December 6, 2017 21:27
-
-
Save Nicknyr/1b90c37679b627d312a30b6a3e37973e to your computer and use it in GitHub Desktop.
Using Axios to make an AJAX request in React (uses Reddit API as an example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import axios from "axios"; | |
export default class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
posts: [] | |
} | |
} | |
componentDidMount() { | |
axios.get(`http://www.reddit.com/r/${this.props.subreddit}.json`) | |
.then(res => { | |
const posts = res.data.data.children.map(obj => obj.data); | |
this.setState({ posts }); | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>Top stores from Reddit/hockey</h1> | |
<ul> | |
{this.state.posts.map(post => | |
<li key={post.id}>{post.title}</li> | |
)} | |
</ul> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<App subreddit="hockey"/>, | |
document.getElementById('render-target') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment