next.js 如何从RTK查询端点访问我存储?

e0uiprwp  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(169)

我想访问我的redux-toolkit存储在rtk-query端点中的数据。
如何从querytransformResponse方法访问存储?

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
wr98u20j

wr98u20j1#

querytransformResponse都不能直接访问Redux状态,但是,您可以将两者替换为queryFn。对于queryFn,所使用的查询函数被传递给查询arg、基本查询api对象、任何已定义的extraOptionsbaseQuery函数。使用api.getState访问当前状态值。
例如,您的代码可能类似于以下内容:

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 };
        }
      },
    }),
  })
});

相关问题