Where do we get this data from?
Does this work?
Does not work! – The render function is not async.
Well, how about this?
Does not work! – When the promise resolves, the render function already ran.
Fetching data asynchronously requires state management.
→useState
Bad! – This produces an infinte loop.
Handle side effects with useEffect
This works! , but ...
What's going on here?
index.tsx
In development, when using Strict Mode , components are re-mounted: mount, unmount, mount
Purpose: future-proofing the app
In development, when using Strict Mode , components are re-mounted: mount, unmount, mount
Purpose: future-proofing the app
→ Effects are executed at least twice in development
(not in prod)
Therefore it is recommanded to not fetch data with useEffect but rely on a library, so let's do it!
Configure TanStack Query
npm i @tanstack/react-query
Using Tanstack Query for data fetching
Clean & simple – also comes with with retry, cache & more functionality
Since we are using TypeScript, we should always work with defined types—avoid any !
export async function fetcher<T>(uri: string): Promise<T> {
const response = await fetch(uri);
if (!response.ok) throw new Error('Could not fetch data!');
return response.json();
};
https://pokeapi.co/api/v2/pokemon?limit=5
{
...
"results": [
{
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
},
...
]
}
List.tsx
We learned…