Browse Source

Add ajax with hooks example (#2803)

* Add ajax with hooks example

* Add comment about empty deps in useEffect hook

* grammar

Co-authored-by: Alex Krolick <alexkrolick@users.noreply.github.com>
main
Gordey 5 years ago
committed by GitHub
parent
commit
7551fdf2df
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 47
      content/docs/faq-ajax.md

47
content/docs/faq-ajax.md

@ -82,3 +82,50 @@ class MyComponent extends React.Component {
}
}
```
Here is the equivalent with [Hooks](https://reactjs.org/docs/hooks-intro.html):
```js
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.items);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
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