2/2 Series: RTK Query

RTK Query - continued

The continuation of the RTK Query series: fetching and updating data with createApi, controlling how long data stays in the cache with keepUnusedDataFor, automatic refetching with tags, and cache keys that distinguish between different parameters.

Introduction

RTK Query is a library for fetching data and caching it, and it is part of Redux Toolkit (RTK). It is designed to simplify working with APIs: fetching the data, managing the loading and error states, and storing the results in the Redux store.

The library generates a ready-made hook for every endpoint. The hooks fetch the data from the API and manage it in the Redux store automatically. It also has tools for caching, polling and pagination, which makes it easier to build complex data-driven applications.

One of its main advantages is a uniform way to fetch data across the whole application. This makes it easy to stay consistent, and the amount of boilerplate code you need to write is much smaller.

In this post we will go through a complete example: fetching data, updating it, controlling how long it stays in the cache, and what happens when the query’s parameters change.

Defining the API

Suppose there is an API endpoint that returns a list of users. This is how you define it with RTK Query, together with an endpoint for updating a user:

JavaScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const usersApi = createApi({
  reducerPath: 'usersApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/api' }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
    }),
    updateUser: builder.mutation({
      query: ({ id, data }) => ({
        url: `/users/${id}`,
        method: 'PUT',
        body: data,
      }),
    }),
  }),
});

export const { useGetUsersQuery, useUpdateUserMutation } = usersApi;

createApi defines the API. baseQuery tells RTK Query how to send requests, and endpoints defines two endpoints: getUsers, which is a query, and updateUser, which is a mutation. RTK Query generates a hook for each of them.

Fetching data

To fetch data, you use the useGetUsersQuery hook:

JSX
import { useGetUsersQuery } from './usersApi';

function UsersList() {
  const { data, isLoading, error } = useGetUsersQuery();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Failed to load users</div>;
  }

  return (
    <ul>
      {data.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

The hook sends a request to the /users endpoint when the component mounts, and stores the result in the Redux store. Another component that calls the same hook with the same parameter gets the data from the cache, without another request.

Updating data

To update data, you use the useUpdateUserMutation hook:

JSX
import { useState } from 'react';
import { useUpdateUserMutation } from './usersApi';

function UserForm({ user }) {
  const [name, setName] = useState(user.name);
  const [email, setEmail] = useState(user.email);
  const [updateUser, { isLoading, error }] = useUpdateUserMutation();

  const handleSubmit = (e) => {
    e.preventDefault();

    updateUser({ id: user.id, data: { name, email } });
  };

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Failed to save</div>;
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </label>
      <label>
        Email:
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      <button type="submit">Save</button>
    </form>
  );
}

The hook returns an array. The first item is the function that triggers the mutation, here updateUser, and the second is an object with the request’s state. When the function is called, RTK Query sends a PUT request to the /users/:id endpoint with the updated data.

How long data stays in the cache

RTK Query keeps the result of a query as long as some component is using it. When the last component stops using the data, it stays in the cache for another 60 seconds by default, and is then removed.

This period is set with the keepUnusedDataFor option, and its value is in seconds. It can be set for the whole API, and it can be overridden for a specific query:

JavaScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const usersApi = createApi({
  reducerPath: 'usersApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/api' }),
  tagTypes: ['User'],
  keepUnusedDataFor: 60, // default for every query, in seconds
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
      keepUnusedDataFor: 60 * 60, // keep unused data for 1 hour
      providesTags: ['User'],
    }),
    updateUser: builder.mutation({
      query: ({ id, data }) => ({
        url: `/users/${id}`,
        method: 'PUT',
        body: data,
      }),
      invalidatesTags: ['User'],
    }),
  }),
});

export const { useGetUsersQuery, useUpdateUserMutation } = usersApi;

In this example the getUsers query keeps unused data for an hour, that is 60 * 60 seconds, instead of 60 seconds. Note that the value is in seconds, not milliseconds.

The option exists only for queries. A mutation’s result is not cached the way a query’s result is, so a mutation has no such setting.

Refreshing the data after an update

After a user has been updated, the list of users in the cache is no longer up to date. In RTK Query the mutation signals this with tags, and all three parts appear in the previous example:

  • In tagTypes you declare the tag types.
  • In providesTags the query marks its result with the User tag.
  • In invalidatesTags the mutation invalidates the tag.

After the update finishes, RTK Query refetches the list of users for the components that display it.

Different parameters, separate cache entries

A query’s cache key is made of the endpoint’s name and the parameter passed to it. A call with the same parameter returns the data from the cache, and a call with a different parameter creates a separate cache entry and sends a new request. In other words, no special setting is needed to keep a query with other parameters from getting the data of an earlier query.

One important thing to know: the query function receives only one parameter. When several values are needed, you pass them in a single object:

JavaScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const usersApi = createApi({
  reducerPath: 'usersApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/api' }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: ({ page, pageSize }) => ({
        url: '/users',
        params: { page, pageSize },
      }),
    }),
  }),
});

export const { useGetUsersQuery } = usersApi;

And this is how you call the hook:

JavaScript
const { data, isLoading, error } = useGetUsersQuery({ page: 1, pageSize: 20 });

Each combination of page and pageSize gets its own cache entry. Moving to page 2 sends a new request, and going back to page 1 shows the stored data right away, as long as it is still in the cache.

A custom cache key

You can also set the cache key yourself, for example when there is a parameter that should not affect it. To do so, you define serializeQueryArgs in the endpoint:

JavaScript
getUsers: builder.query({
  query: ({ page, pageSize, requestedBy }) => ({
    url: '/users',
    params: { page, pageSize },
    headers: { 'X-Requested-By': requestedBy },
  }),
  // the cache key is built from page and pageSize only
  serializeQueryArgs: ({ queryArgs }) => {
    const { page, pageSize } = queryArgs;
    return { page, pageSize };
  },
}),

Here two calls with the same page and the same page size share one cache entry, even when the value of requestedBy is different.

serializeQueryArgs receives one object with three fields:

  • queryArgs: the parameter passed to the hook. In the call useGetUsersQuery({ page: 1, pageSize: 20 }) it is the object { page: 1, pageSize: 20 }.
  • endpointName: the endpoint’s name, here 'getUsers'.
  • endpointDefinition: the endpoint’s definition, that is, what was passed to builder.query: the fields query, providesTags, keepUnusedDataFor and all the rest.

The function can return a string, and then the string is the cache key as it is. It can also return an object, a number or a boolean, and then RTK Query builds the key from them in its usual way, together with the endpoint’s name.

Here is an example that builds the key as a string, with the endpoint’s name at its start:

JavaScript
getUsers: builder.query({
  query: ({ page, pageSize }) => ({
    url: '/users',
    params: { page, pageSize },
  }),
  serializeQueryArgs: ({ queryArgs, endpointName }) =>
    `${endpointName}:${queryArgs.page}:${queryArgs.pageSize}`,
}),

The endpoint’s name in the key makes sure that two endpoints that take the same parameters are cached separately. When you return a string, making sure the key is unique is your responsibility.

Summary

  • createApi defines the endpoints, and RTK Query generates a hook for each of them.
  • keepUnusedDataFor sets how many seconds data that no component is using stays in the cache. The default is 60.
  • Tags (tagTypes, providesTags, invalidatesTags) cause a refetch after a mutation.
  • Each different parameter gets its own cache entry, and serializeQueryArgs lets you set the key yourself.

Search and commands