diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index 102e1c07..74a9a81e 100644 --- a/content/docs/faq-ajax.md +++ b/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
Error: {error.message}
; + } else if (!isLoaded) { + return
Loading...
; + } else { + return ( + + ); + } +} +```