Created
September 5, 2019 12:50
-
-
Save HelloAlberuni/995f034a4e98d9b878811702ceb07324 to your computer and use it in GitHub Desktop.
React fetch post by axios
This file contains hidden or 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 './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