Search code examples
reactjsreduxreact-reduxredux-toolkitrtk-query

How can I get data from my store generated by RTK Query?


I'm using a very basic RTK Query hook to get some user data from an API. How can I access the data saved in my store inside of my components? I'm not able to get the data from the store generated in a specific matter by RTK Query.

I have a simple Post API and I called the getPosts hook. In Redux devtools I can see the data from the RTK query hook in my store:

Post API

import { createApi, fetchBaseQuery } from '@rtk-incubator/rtk-query';

export interface Post {
  id: number;
  name: string;
  fetched_at: string;
}

type PostsResponse = Post[];

export const postApi = createApi({
  reducerPath: 'postsApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  entityTypes: ['Posts'],
  endpoints: (build) => ({
    getPosts: build.query<PostsResponse, void>({
      query: () => 'posts',
      provides: (result) => [
        ...result.map(({ id }) => ({ type: 'Posts', id } as const)),
        { type: 'Posts', id: 'LIST' },
      ],
    }),
  }),
});

Posts saved in store after hook was called

enter image description here


Solution

  • The easiest way is to just call the getPosts hook in every component that needs the data. It will use the data from the cache and not make an extra request - but if you later mount that component without a parent component, or in another context where the data was not present yet, it will make the request.

    So you are guaranteed to always have the data at hand that way.