Browse Source

Handle more states in async example code

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

52
content/docs/faq-ajax.md

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

Loading…
Cancel
Save