4

I'm trying to select cached data from RTKQ without using the auto-generated query hook, but I'm having trouble understanding the docs

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

This is how the docs describe how to access the data, but I can't find any references on how to inject the state object "select()(state)".

I can't figure out how to access the data if I only call the select?

api.endpoints.getPosts.select()

Can someone explain me the difference between "select()" and "select()(state)"

Or what is the optimal solution to access the cached data from RTKQ?

dev.tom
  • 489
  • 2
  • 5
  • 16

2 Answers2

3

The result of api.endpoints.getPosts.select() is a selector function for the result of using the "getPosts" endpoint without arguments.

Similarly, result of api.endpoints.getPosts.select({ page: 5 }) is a selector function for the result of using the "getPosts" endpoint the argument { page: 5 }.

A selector function is then called as selector(state) or passed into useSelector(selector).

If you write that altogether, you end up with api.endpoints.getPosts.select()(state).

phry
  • 35,762
  • 5
  • 67
  • 81
  • What if we are doing this in mapstateToProps and there are lot of destructure state already ? – Probosckie Oct 13 '22 at 12:36
  • @Probosckie You really should not use any of those selectors in `mapStateToProps`. RTK Query works a *lot* better with hooks in function components. If you do not have an application you cannot upgrade to React 16 (which is over 5 years old) you should definitely use function components and the hooks. Classes are a legacy concept and connect is a legacy api just for compatibility with old class implementations. – phry Oct 13 '22 at 13:25
1

@phry

Thank you for your answer! I'm not 100% sure I understood your answer. But it pointed me in a direction that enabled me to get the data.

I ended up creating a selector like the docs.

export const selectUser = (state) => userApi.endpoints.getUser.select()(state);

and in my function, I referenced it with getting the exported store from configureStore() method

const { data } = selectUser(store.getState());

But I'm not sure if this is the intended way to do it.

dev.tom
  • 489
  • 2
  • 5
  • 16