Tengo un controlador de API con diferentes funciones que usan Axios para obtener, publicar, parchear, etc. Quiero usar esos controladores de API con createAsyncThunk del kit de herramientas redux, ¿es posible?
sería algo como
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; }, );Lo que pasa aquí es que createAsyncThunk maneja las promesas de respuesta rechazadas, cumplidas y pendientes, pero si uso esta configuración, siempre se devolverá cumplida aunque la llamada realmente falle.
Puede usar la función de unwrap para hacer que createAsyncThunk devuelva errores en la instrucción catch . Compruebe el siguiente ejemplo.
Sin unwrap() :
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 }) Con unwrap() :
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) })