Skip to content

Instantly share code, notes, and snippets.

@HelloAlberuni
Created September 5, 2019 12:50
Show Gist options
  • Select an option

  • Save HelloAlberuni/995f034a4e98d9b878811702ceb07324 to your computer and use it in GitHub Desktop.

Select an option

Save HelloAlberuni/995f034a4e98d9b878811702ceb07324 to your computer and use it in GitHub Desktop.
React fetch post by axios
import React, { Component } from 'react'
import './App.css';
import Books from './Books/Books';
import axios from 'axios'
class App extends Component{
state = {
posts: []
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.setState({
posts: response.data
})
})
.catch(error => console.log(error))
}
render(){
if(this.state.posts.length === 0){
return <h1>Loading....</h1>
} else {
return (
<ol>
{this.state.posts.map((val, i) => {
return <li key={i}>{val.title}</li>
})}
</ol>
)
}
}
}
export default App;
// Lifecycle
// constructor
// render
// call all lifecycle methods
// componentDidMount
// componentDidUpdate
// componentWillUnmount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment