Skip to content

Instantly share code, notes, and snippets.

@Nicknyr
Last active December 6, 2017 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nicknyr/1b90c37679b627d312a30b6a3e37973e to your computer and use it in GitHub Desktop.
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)
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