Created
June 14, 2023 02:37
-
-
Save ernestlv/a09ae09526c109dfa749de9a1bebc90c to your computer and use it in GitHub Desktop.
Async call in React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Main = () => { | |
useEffect(() => { // runs after Main component is rendered | |
async function init() { | |
console.log('fetching suggestions ...'); | |
let response; | |
try { | |
response = await fetch('https://pokeapi.co/api/v2/pokemon/'); | |
response = await response.json(); | |
} catch( e ) { | |
response = Promise.resolve({ results:[] }); | |
} finally { | |
console.log('fetched response', response); | |
} | |
console.log('fetching suggestions done.'); | |
}; | |
init(); | |
}, []); // empty array make sure it only runs once | |
console.log("render Main..."); | |
return ( | |
<h1>Hello World!!!</h1> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Further reading
https://devtrium.com/posts/dependency-arrays
https://devtrium.com/posts/async-functions-useeffect
https://react.dev/learn/synchronizing-with-effects
https://react.dev/reference/react/StrictMode