Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I access my store from RTK-Query endpoints?

I want to access to my redux-toolkit store data inside of the rtk-query endpoints.

how can I access my store from query or transformResponse methods?

import { createApi } from '@reduxjs/toolkit/query/react'
import customFetchBase from './customFetchBase.js'
import { setUserInfo, setUserPermissions } from '../features/userSlice.js'
import { aesDEC } from 'src/util/public.util.js'

export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: customFetchBase,
  endpoints: builder => ({
    getUser: builder.mutation({
      query: () => ({
        url: '/Account/Login/GetUserInfo',
        method: 'POST',
        body: {
          RequestVerificationToken: salt //here I want the salt from my redux store
        }
      }),
      transformResponse: response => {
        return aesDEC(response.data, salt); //here I want the salt from my redux store
      },
    }),
})
export const { useGetUserMutation } = authApi
like image 556
Alireza Kordkheili Avatar asked Oct 28 '25 03:10

Alireza Kordkheili


2 Answers

Neither query nor transformResponse have direct access to the Redux state, however, you can replace both with the queryFn which does. With queryFn the query function used is passed the query arg, the base query api object, any defined extraOptions, and the baseQuery function. Use api.getState to access the current state value.

Example, your code might look similar to the following:

export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: customFetchBase,
  endpoints: builder => ({
    getUser: builder.mutation({
      queryFn: async (arg, api, extraOptions, baseQuery) => {
        const state = api.getState();
        const salt = state./* path to salt state value */;

        try {
          const { data } = await = baseQuery({
            url: '/Account/Login/GetUserInfo',
            method: 'POST',
            body: {
              RequestVerificationToken: salt
            }
          });
          return { data: aesDEC(data, salt) };
        } catch(error) {
          return { error };
        }
      },
    }),
  })
});
like image 136
Drew Reese Avatar answered Oct 30 '25 22:10

Drew Reese


You can also get access to the state in fetchBaseQuery/prepareHeaders function like this if you need to set Auth or some general header:

export const DataApi = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ 
    baseUrl: `${process.env.REACT_APP_API_URL}`, 
    prepareHeaders: (headers, {getState}) => {
      const state = getState();
      headers.set(HEADER_AUTH, state?.auth?.value?.authorization);
    }
  }),
 ...
});
like image 22
Gepetto1972 Avatar answered Oct 30 '25 22:10

Gepetto1972