Data Fetching

Essential React

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
  • Using the Fetch standard browser API is not straightforward to use due to its asynchronicity
  • Therefore a data fetching library

We will use TanStack Query in this course

Configure TanStack Query

npm i @tanstack/react-query

Using Tanstack Query for data fetching

Clean & simple – also comes with retry, cache & more functionality

The loading state can also be handled with React's Suspense for Data Fetching API (opt-in).

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 & details from the PokeAPI .
  • Install TanStack Query : npm i @tanstack/react-query
  • API call with TanStack Query:
    GET https://pokeapi.co/api/v2/pokemon?limit=1000
    GET https://pokeapi.co/api/v2/pokemon/{name}
  • 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 https://pokeapi.co/api/v2/pokemon/bulbasaur

Poke-API DTOs

pokeApi.ts

Solution

ListPage.tsx

DetailPage.tsx

Mutating resources

Why doesnt useQuery fit?

  • useQuery Hook is resolved immediately – we want to mutate upon a form submit or button click
  • useQuery results are cached, which makes no sense in mutations

useMutation

Note how there is no query key and no data.

useMutation cache update

You can even go further to use optimistic UI to update the cache prior to the mutation and rollback in the error case.

Data Fetching Libraries

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

An extensive overview and comparison can be found on the TanStack Query website.

Recap

We learned…

  • How to fetch data in React with a library
  • Display details relating to loading & errors
  • Using useMutation for data manipulation
  • How to update the local cache without refetch

Questions?