官方文档展示了如何在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
},
})
auth
的token
来自这里的一个切片(参见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
?
1条答案
按热度按时间y4ekin9u1#
尝试: