Skip to content

Instantly share code, notes, and snippets.

@carlows
Last active September 9, 2017 18:30
Show Gist options
  • Save carlows/82b9d65370347eb2b4f4258ef8815d53 to your computer and use it in GitHub Desktop.
Save carlows/82b9d65370347eb2b4f4258ef8815d53 to your computer and use it in GitHub Desktop.
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
// Necesitas crear el component como una clase
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
// Asi puedes usar los lifecycle methods de React, como componentDidMount()
componentDidMount() {
// Acá haces tu llamada al API
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 }); // Acá la promesa se resuelve y puedes actualizar el state del component con la data
});
}
render() {
return (
<div>
<h1>{`/r/${this.props.subreddit}`}</h1>
<ul>
{this.state.posts.map(post =>
<li key={post.id}>{post.title}</li>
)}
</ul>
</div>
);
}
}
ReactDOM.render(
<FetchDemo subreddit="reactjs"/>,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment