如何将值从createApi存储到redux存储?

laik7k3q  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(151)

我正在尝试存储一个用户数据的值(名字,电子邮件和其他),它是使用createApi来redux存储的。但是我不知道如何做,也不知道什么是好的做法。
用户Api.js文件

export const userApi = createApi({
  reducerPath: "userApi",
  baseQuery: fetchBaseQuery({ baseUrl: "http://localhost:5000" ,
  credentials: "include",
  tagTypes: ['Users'],
  prepareHeaders: (headers, { getState }) => {
    const { accessToken } = getState().auth;
    if (accessToken) {
      headers.set('Authorization', `Bearer ${accessToken}`);
    }

    return headers;
  }
  }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => "/users",
      // this is used when when we want to validate and update UI
      providesTags:["Users"],
      //this is used to specify which object we wanna show
      transformResponse: (response) => response.data,
    }),
    loginUser : builder.mutation({
      query: (value) => ({
        url : "/login",
        method : "POST",
        body : value,
      })
    }),

export const { 
    useGetUsersQuery, 
    useLoginUserMutation} = userApi;

我正在尝试将值放入此slice. authSlice.js文件的状态中

const initialState = {
    user: null,
    accessToken : null,
}

const authSlice = createSlice({
    name : "auth",
    initialState,
    reducers: {
        setUser: (state, action) =>{
            state.user = action.payload ;
        },
        setAccessToken: (state, action) =>{
            state.accessToken = action.payload;
        },
        logOut: () => initialState
    },
})

export const { setUser, setAccessToken, logOut } = authSlice.actions;

export default authSlice.reducer

export const selectUser = (state) => state.auth.user;
export const selectAccessToken = (state) => state.auth.accessToken;

我以前看过一个教程,我记得你可以使用extraReducer和addCase,但我不记得视频名称,我不知道这是否是一个很好的实践,所以有人能告诉我正确的方法和良好的实践方式。
谢谢。

6tqwzwtp

6tqwzwtp1#

您可以执行以下操作:

import { setUser, setAccessToken } from '[API/PATH]';

那么你可以在onCacheEntryAdded中访问dispatch。你也可以在queryFn中这样做,你可以像queryFn: (value, { dispatch }) => ...一样将dispatch作为第二个参数

loginUser : builder.mutation({
      query: (value) => ({
        url : "/login",
        method : "POST",
        body : value,
      })
    }),
    async onCacheEntryAdded(arg, { cacheDataLoaded, dispatch, getCacheEntry }) {
                await cacheDataLoaded;
                const result = getCacheEntry();
                const { data } = result;
                const { accessToken } = data;
                dispatch(setUser(data));
                dispatch(setAccessToken(accessToken))
            },

相关问题