Is it possible to use an external SDK or data fetching library like Kitsu with RTK Query/Redux Toolkit?

Viewed 968

According to the RTK Query documentation, I can create queries like the following:

export const projectsApi = createApi({
  reducerPath: 'projects',
  baseQuery: fetchBaseQuery({
    baseUrl: "https://some-site.com/api/",
    prepareHeaders: (headers) => {
      headers.set('Authorization', `Bearer ${accessToken}`);

      return headers;
    },
  }),
  tagTypes: ['Project'],
  endpoints: (builder) => ({
    fetchProjects: builder.query<Project[], void>({
      query: () => ({ url: `projects` }),
    }),
  }),
});

The above works as expected. However, if want to use an external library like Kitsu to fetch and transform the data, I get the following error:

RTK query error

Here is my updated code while using with Kitsu:

export const projectsApi = createApi({
  reducerPath: 'projects',
  baseQuery: fetchBaseQuery({
    baseUrl: "https://some-site.com/api/",
  }),
  tagTypes: ['Project'],
  endpoints: (builder) => ({
    fetchProjects: builder.query<Project[], void>({
      query: api.get('projects'),
    }),
  }),
});

Here is the code for the api function:

const kitsu = (accessToken: string) => {
  return new Kitsu({
    baseURL: "https://some-site.com/api/",
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`,
    },
  });
};

const api = kitsu("ey....");

Is it possible to override the baseQuery function of RTK Query/Redux Toolkit with the one that Kitsu or any 3rd party package provides?

1 Answers

Yes, there's a couple options here:

  • You can create your own function that implements the "base query" behavior and use that as the baseQuery option of the API slice
  • You can override individual endpoints by giving them a queryFn option, which can be any async function that fetches some data and returns it in the right format.

See the "Customizing Queries" page in the RTK Query preview docs for instructions on how to do both of those.

Related