Browse Source

Handle more states in async example code

main
Alex Krolick 7 years ago
parent
commit
b1d64dc8a2
  1. 56
      content/docs/faq-ajax.md

56
content/docs/faq-ajax.md

@ -31,30 +31,46 @@ The example API returns a JSON object like this:
```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isLoaded: false,
error: null,
items: [],
}
}
state = {
error: null,
isLoaded: false,
items: []
};
componentDidMount() {
fetch('https://api.example.com/items')
fetch("https://api.example.com/items")
.then(res => res.json())
.then(result => this.setState({items: result.items))
.catch(err => this.setState({ err: error }))
.then(result =>
this.setState({
isLoaded: true,
items: result.items
})
)
.catch(error =>
this.setState({
isLoaded: true,
error
})
);
}
render() {
const {error, items} = this.state
if (err) return <div>{error}</div>
return (
<ul>
{ items.map(item => <li>{item.name} {item.price}</li> }
</ul>
)
const { error, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading ...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
```

Loading…
Cancel
Save