typescript 在另一个prepareHeaders中访问另一个RTK查询createApi的getState?

xmakbtuz  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(109)

官方文档展示了如何在prepareHeaders中访问auth切片。我想做同样的事情,除了我没有切片,但使用RTK Query的createApi获取并保存auth“状态”。

import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import type { RootState } from './store'

const baseQuery = fetchBaseQuery({
  baseUrl: '/',
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).auth.token

    // If we have a token set in state, let's assume that we should be passing it.
    if (token) {
      headers.set('authorization', `Bearer ${token}`)
    }

    return headers
  },
})

authtoken来自这里的一个切片(参见https://github.com/reduxjs/redux-toolkit/blob/6 f0 b3 f1 a72 d 7 f6 a39 eb 9585 adba 9 eb 3ef 7277 a58/examples/query/react/authentication/src/features/auth/authSlice. tsx#L7):

type AuthState = {
  user: User | null
  token: string | null
}

const slice = createSlice({
  name: 'auth',
  initialState: { user: null, token: null } as AuthState,
  reducers: {
    setCredentials: (
      state,
      { payload: { user, token } }: PayloadAction<{ user: User; token: string }>
    ) => {
      state.user = user
      state.token = token
    },
  },
})

然而,在我的例子中令牌存储在由**createApi**创建的状态“切片”中,而不是createSlice

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

type KeycloakResponse = {
  access_token: string;
};

export const keycloakApi = createApi({
  reducerPath: "keycloakApi",
  baseQuery: fetchBaseQuery({ baseUrl: "/redirect" }),
  tagTypes: [],
  endpoints: (builder) => ({
    getKeycloakAccessToken: builder.query<KeycloakResponse, void>({
      query: () => `/?info=json&access_token_refresh_interval=0`,
    }),
  }),
});

如何在prepareHeaders中访问此access_token
如果我尝试使用getState(),我无法访问它?x1c 0d1x
如何在另一个createApi prepareHeader中访问其accessToken

y4ekin9u

y4ekin9u1#

尝试:

prepareHeaders(headers, { getState }) {
  const state = (getState as typeof store.getState)();
  const {
    keycloakApi: { access_token },
  } = state;

  headers.set("token", access_token);
  return headers;
},

相关问题