axios/ async/ await /own API
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<div id="root"></div>
Babel + JSX
//https://css-tricks.com/using-data-in-react-with-the-fetch-api-and-axios/
class App extends React.Component {
state = {
posts: [],
isLoading: true,
errors: null
};
/* getPosts() {
axios
.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json")
.then(response => {
this.setState({
posts: response.data.posts,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
} */
async getPosts() {
const response = await axios.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json");
try {
this.setState({
posts: response.data.posts,
isLoading: false
});
} catch (error) {
this.setState({ error, isLoading: false });
}
}
componentDidMount() {
this.getPosts();
}
render() {
const { isLoading, posts } = this.state;
return (
<React.Fragment>
<h2>Random Post</h2>
<div>
{!isLoading ? (
posts.map(post => {
const { _id, title, content } = post;
return (
<div key={_id}>
<h2>{title}</h2>
<p>{content}</p>
<hr />
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));