Essential React
Data Fetching

Where do we get this data from?

PokeAPI

Documentation

List of Pokemon

GET https://pokeapi.co/api/v2/pokemon?limit=5

What to use for data fetching?

  • React does not provide data fetching
  • Fetch: standard browser API
  • … or any data fetching library

Fetch

How can we use fetch in React?

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.

Why we should not run side effects in the render function

  • We don't want the side effect to execute with every render.
  • The render function might be executed anytime – we don't control it.
  • In the render function we just want to render and not spend computing on other tasks.

Handle side effects with useEffect

This works! , but ...

Duplicate request

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

In a future release, the loading state can be handled with Suspense

Some words about types

            
              

Since we are using TypeScript, we should always work with defined types—avoid any !

Exercise

  • Retrieve the data for the pokemon list from the PokeAPI .
  • Install TanStack Query : npm i @tanstack/react-query
  • API call with TanStack Query: GET https://pokeapi.co/api/v2/pokemon?limit=50
  • Stretch goal: Display loading & error messages
TanStack Query : npm i @tanstack/react-query
              
                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/"
                            },
                            ...
                        ]
                    }
                
            

Solution

List.tsx

Data Fetching Libraries

  • TanStack Query
  • SWR
  • Axios (for fetch abstraction)
  • Apollo Client (GraphQL)

Recap

We learned…

  • Why fetching data is tricky with React render mechanism
  • How to fetch data in React with a library
  • Display details relating to loading & errors

Questions?