we use built-in fetch to get data from a url say…https://api.example.com/items:
1 |
fetch('https://api.example.com/items') |
Once we have retrieved it, we execute json() on the response ‘res’, which is a JSON BODY mixin.
1 2 |
fetch('https://api.example.com/items') .then(res => res.json()) |
It returns a promise that resolves with the result of parsing the body text as JSON:
1 2 3 4 5 6 7 |
fetch('https://api.example.com/items') .then(res => res.json()) .then( // promise (result) => { } ) |
We then set our state object property employees to that result. When we use setState, React sees that a state property was updated, and goes to diff the virtual DOMs. Thus, the render gets triggered again so that we re-draw the subtree that changed.
1 2 3 4 5 6 7 8 9 10 11 12 |
fetch('https://api.example.com/items') .then(res => res.json()) .then( (result) => { this.setState({ employees: result.employees }) }, (error) => { this.setState({ error }) } ) |
Notice we put the fetch inside of componentDidMount. The reason why is because the component needs to execute constructor, componentWillMount, then start building up its DOM, and finally when done, call componentDidMount first in order to have the states and nodes in place. Only when our DOM nodes and states are ready, can we then insert data. Thus, that is why we fetch in componentDidMount.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
componentDidMount() { fetch('https://api.example.com/items') .then(res => res.json()) .then( (result) => { this.setState({ employees: result.employees }) }, (error) => { this.setState({ error }) } ) } |
full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class MyComponent extends React.Component { constructor(props) { super(props) this.state = { employees: [], error: null } } componentDidMount() { fetch('https://api.example.com/items') .then(res => res.json()) .then( (result) => { this.setState({ employees: result.employees }) }, (error) => { this.setState({ error }) } ) } render() { const { error, employees } = this.state if (error) { return <div>Error: {error.message}</div>; } else { return ( <ul> {employees.map(employee => ( <li key={employee.name}> {employee.name}-{employee.experience} </li> ))} </ul> ) } } } |