通过 CreateAsyncThunk 使用 RTK 突变

问题描述 投票:0回答:1

我想从 auth 切片创建登录 API 调用。我在项目中同时使用了redux工具包和rtk查询。我想在 API 调用中使用 fetchbasequey。我已经预先定义了baseQuey。

export const baseQuery = retry(fetchBaseQuery({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'Access-Control-Allow-Origin': '*',
    },
    prepareHeaders: (headers, { getState }) => {
        const accessToken = localStorage.getItem(AUTH_TOKEN_KEY) || '';
        const uid = getLocal(UID_KEY);
        if (accessToken) {
            headers.set('Authorization', accessToken);
            headers.set(UID_KEY, uid);
        }
        return headers;
    },
}),{maxRetries: 3});

我的期望是在 authSlice 中使用 rtk 突变。我已经尝试过这样的。但它不起作用。如果这种方式不可能,请建议我一个创建此后端连接的好方法。

export const loginAsync = createAsyncThunk(
    'auth/login',
    async (credentials: LoginValuesType, thunkAPI) => {
        try {
            //how to call the mutation here?
            //const response = await userApi.useLoginMutation(credentials)
    
            if (response?.data?.code === 0) {
                localStorage.setItem(AUTH_TOKEN_KEY, response.data?.data?.token);
                setLocal('uid', response.data?.data?.uid);
                return response.data;
            } else if(response?.data?.code === 1){
                thunkAPI.dispatch(showError(response?.data?.msg))
                return thunkAPI.rejectWithValue({msg: response?.data?.msg})
            }
        } catch (e) {
            thunkAPI.dispatch(showError('An error occurred'))
            return thunkAPI.rejectWithValue({msg: "An error occurred"})
        }
    }
)

这是我实现的 rtk 突变。 (如果不需要的话我们可以将其删除)

export const userApi = createApi({
    reducerPath: 'userApi',
    baseQuery: baseQuery,
    endpoints: (builder) => ({       
        login: builder.mutation({
            query: (args) => {
                return {
                    url: '/api/v1/sign_in',
                    method: 'POST',
                    body: args,
                }
            },
        }),
    }),
});

export const {
    useLoginMutation
} = userApi;
reactjs redux-toolkit redux-thunk rtk-query
1个回答
0
投票

您可以直接启动端点。示例:

export const loginAsync = createAsyncThunk(
  'auth/login',
  async (credentials: LoginValuesType, thunkApi) => {
    try {
      const { data } = await thunkApi.dispatch(
        userApi.endpoints.login.initiate(credentials);
      );
    
      if (data.code === 0) {
        localStorage.setItem(AUTH_TOKEN_KEY, data.data?.token);
        setLocal('uid', data.data?.uid);
        return data;
      } else if (data.code === 1) {
        const { msg } = data;
        thunkApi.dispatch(showError(msg));
        return thunkApi.rejectWithValue({ msg });
      }
    } catch (e) {
      thunkApi.dispatch(showError('An error occurred'));
      return thunkApi.rejectWithValue({ msg: "An error occurred" });
    }
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.