From 7551fdf2dff5b287d247448e7edcdd7f44df0f99 Mon Sep 17 00:00:00 2001 From: Gordey Date: Wed, 1 Apr 2020 01:32:11 +0600 Subject: [PATCH] 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 --- content/docs/faq-ajax.md | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) 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 ( + + ); + } +} +```