React Native Data Management

Server cache is not the same as UI state, and should be handled differently.

What you will learn

  • Fetch data over the network from the Star Wars API
  • Display status and datas with useQuery
  • Use an advanced React Pattern: Context API
  • Create a custom hook

👾 Before we start the exercise

Here's how it works:

  1. Write your data fetching functions
  2. Wrap them in a named query
  3. react-query handles caching, deduping, re-fetching, and loading states
async function fetchData(itemId) {
  const res = await fetch(`https://example.com/api/${itemId}`);
  const json = await res.json();
  return json;
}

function Component({ itemId }) {
  const { isLoading, data } = useQuery(['fetchData', itemId], fetchData);

  if (isLoading) {
    return <Text>Loading…</Text>;
  } else {
    return <DoStuffWithData data={data} />;
  }
}

Back to the example we had before.

👨‍🚀 Exercise 1

That's the screen we will create: a list of data

Starships list

  • Install the library with yarn
yarn add react-query
  • Add a QueryClientProvider and wrap the application entry point of your application. You can have a look at the QueryClientProvider documentation (Do you remeber App.tsx?).

  • Take 5 min to readt the react-query documentation.

  • In the example isLoading and isError lives on the same files. To have a more robust application, we can wrap our queries into one custom hook useStarships().

The logic is:

  1. fetch data from the endpoint and return the result as a json
  2. get the result from the fetch and return the result of useQuery
  3. use our custom hook to render the UI
// ./hooks/useStarships.ts
import { useQuery } from 'react-query';

async function fetchData() {
  const res = await fetch(`https://swapi.dev/api/starships/`);
  const json = await res.json();
  return json;
}

export function useStarships() {
  return useQuery(['starships'], fetchData);
}

👏 Now you can write useStarships() anywhere in your Screen and React Query handles the rest.

  • Use useStarships hooks to dislay a loading message.
  • Use useStarships hooks to handle errors.
  • Use useStarships hooks to render data.

👽 Bonus