Browse Source

Handle more states in async example code

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

44
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)
this.state = {
isLoaded: false,
error: null, error: null,
items: [], isLoaded: false,
} 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 <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading ...</div>;
} else {
return ( return (
<ul> <ul>
{ items.map(item => <li>{item.name} {item.price}</li> } {items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul> </ul>
) );
}
} }
} }
``` ```

Loading…
Cancel
Save