Search code examples
react-nativereduxredux-thunkrtk-query

How to access the state using Redux RTK in react native app


I'm using Redux RTK query in my react native project and I can't figure out how to access the state without firing the query each time.

I created an api with my customBaseQuery

const emptySplitApi = createApi({
  reducerPath: 'api',
  baseQuery: customBaseQuery(),
  endpoints: () => ({})
})

I then injected my endpoints.

export const userApi = emptySplitApi.injectEndpoints({
  endpoints: (builder) => ({
    getUser: builder.query<User, GetUserInput>({
      query: (options) => ({
        query: getUserQuery,
        options: options
      })
    })
  }),
  overrideExisting: true
})

And configured the store:

const persistConfig = {
  key: 'root',
  storage: AsyncStorage
}

const reducers = combineReducers({
  [emptySplitApi.reducerPath]: emptySplitApi.reducer
})

const persistedReducer = persistReducer(persistConfig, reducers)

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false }).concat(emptySplitApi.middleware)
})

When I open the app I call the getUser API using the redux-generated hook. This works and I get the expected response.

const { data } = useGetUserQuery(input)

Now, I need to access the user data in another screen of my app without calling the API again (redux should have cached/persisted the data) but I can't manage to access the state.

I tried the following:

const { getUser } = useAppSelector((state) => state.api.queries)

but getUser is always undefined. However if I print the whole state I can see the data. How can I access the state from anywhere in the app without calling the API again?


Solution

  • Just use your useGetUserQuery(yourOptions) everywhere. It will fire only one request to the server, no matter how many times you use it, and the data will be available everywhere.