Skip to content

Commit b1d64dc

Browse files
committed
Handle more states in async example code
1 parent bac965e commit b1d64dc

File tree

1 file changed

+36
-20
lines changed

1 file changed

+36
-20
lines changed

content/docs/faq-ajax.md

Lines changed: 36 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -31,30 +31,46 @@ The example API returns a JSON object like this:
3131

3232
```jsx
3333
class MyComponent extends React.Component {
34-
constructor(props) {
35-
super(props)
36-
this.state = {
37-
isLoaded: false,
38-
error: null,
39-
items: [],
40-
}
41-
}
42-
34+
state = {
35+
error: null,
36+
isLoaded: false,
37+
items: []
38+
};
39+
4340
componentDidMount() {
44-
fetch('https://api.example.com/items')
41+
fetch("https://api.example.com/items")
4542
.then(res => res.json())
46-
.then(result => this.setState({items: result.items))
47-
.catch(err => this.setState({ err: error }))
43+
.then(result =>
44+
this.setState({
45+
isLoaded: true,
46+
items: result.items
47+
})
48+
)
49+
.catch(error =>
50+
this.setState({
51+
isLoaded: true,
52+
error
53+
})
54+
);
4855
}
49-
56+
5057
render() {
51-
const {error, items} = this.state
52-
if (err) return <div>{error}</div>
53-
return (
54-
<ul>
55-
{ items.map(item => <li>{item.name} {item.price}</li> }
56-
</ul>
57-
)
58+
const { error, items } = this.state;
59+
if (error) {
60+
return <div>Error: {error.message}</div>;
61+
} else if (!isLoaded) {
62+
return <div>Loading ...</div>;
63+
} else {
64+
return (
65+
<ul>
66+
{items.map(item => (
67+
<li key={item.name}>
68+
{item.name} {item.price}
69+
</li>
70+
))}
71+
</ul>
72+
);
73+
}
5874
}
5975
}
6076
```

0 commit comments

Comments
 (0)