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

3

7

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

Avogadro answered 7/3, 2022 at 16:18 Comment(0)
L
7

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.

Lustrum answered 7/3, 2022 at 18:10 Comment(5)
Yes, @phry, exactly. But what if I want to access that data from different components in different contexts? RTK-query never get data from cache and each single call will trigger a new request. What's the profit of the concept? To provide cache in one component only?Constitutional
@Григорий if you call the useGetPostsQuery in all components with the same argument, they will use the same cache value and will not trigger any new requests. Are you 100% sure you are seeing new requests there? That should be impossible.Lustrum
@Lustrum I need the result of an api to be general state in all over the project. Which one is better to use ? AsyncThunk or RTK Query ?Jag
What happens if the query fails, the query will be launched on every component you called causing an infinite loopDonoghue
@Donoghue unless those components unmount and mount each other, there will not be a loopLustrum
C
3

You can access data and status try this:

const result = api.endpoints.getPosts.select()(state)
const { data, status, error } = result

and call api without hook:

dispatch(api.endpoints.getPosts.initiate())

see more

Coincidental answered 10/6, 2022 at 9:7 Comment(0)
M
0

As in RTK documentation is explained, the proposed solution is calling useQuery hooks with the same arguments as before it called. It retrieves data from cached enpoints, But as I need too many arguments to send to query hook, and I should send it to other component, so I prefer to use the store object to access data from endpoints as below:

const store = useStore();
const cachedQueries = store.getState().dashboardApi.queries;

Then I made an object with endpoint's name as key and their data as value:

let dashboardResult: { [key: string]: any } = {};        
Object.values(cachedQueries).forEach((item: any) => {
    dashboardResult = { 
       ...dashboardResult,
       ...{ [item?.endpointName]: item?.data?.data }
    }
});
Multicolored answered 27/1, 2023 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.