是否可以使用外部axios处理程序与createAsyncThunk



我有一个API处理程序,使用Axios进行get、post、patch等不同的功能。我想使用那些API处理程序与createAsyncThunk从redux工具包,这是可能的吗?

就像

export const paymentMethods = createAsyncThunk(
'tenants/payments',
async (ppp: any, { dispatch, getState }) => {
const x = await postRequest(
`${API.TENANTS}/${ppp.tenantId}/${API.PAYMENT_METHODS}`,
response => console.log(response),
ppp.data,
);
return x.data;
},
);

这里的事情是createAsyncThunk处理拒绝,完成和挂起的响应承诺,但如果我使用这个配置,它将始终返回完成,即使调用实际上失败。

可以使用unwrap函数使catch语句中的createAsyncThunk返回错误。查看下面的示例。

Withoutunwrap():

dispatch(paymentMethods())
// By default, dispatching asyncThunks never results in errors (errors are just saved at redux)
.then((result) => {
/*
Here you can access the result (success or error) of the asyncThunk.
If we don't use 'unwrap', error (if happens) will be returned here as:
{
error: {name: "AxiosError", message: "Request failed with status code 401", code: "ERR_BAD_REQUEST"}
meta: {arg: {…}, requestId: "3eIa5l0L3J12ADFrkxirt", rejectedWithValue: false, requestStatus: "rejected", aborted: false, …}
payload: undefined
type: "tenants/payments/rejected"
}
*/
console.log(`PaymentMethods result (success or error): `, result)
})
.catch((error) => {
// This WILL NEVER be reached
})

Withunwrap():

dispatch(paymentMethods())
// Using 'unwrap', the internal logic of the reducer doesnt change. 
// But you can access the error in the 'catch' statement. 
.unwrap()
.then((result) => {
// Here you can access the success result of the asyncThunk.
console.log(`PaymentMethods result (success): `, result)
})
.catch((error) => {
/*
Here you can access the error result of the asyncThunk. Example:
{
code: "ERR_BAD_REQUEST"
message: "Request failed with status code 401"
name: "AxiosError"
}
*/
console.log(`PaymentMethods result (error): `, error)
})

相关内容

  • 没有找到相关文章

最新更新