I am using the following createAsyncThunk to delete an application in the db.
For some reason the fetch is not working. handleFetchErrors
throws an Error if the response is not OK
export const handleFetchErrors = (response: Response) => {
if (!response.ok) {
throw Error(response.statusText)
}
}
export const deleteApplication = createAsyncThunk("applications/deleteApplication", async (data: any) => {
try {
const response = await fetch(`/api/application/${data.id}`, {
method: "DELETE",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json",
},
});
//fixme: call still gets fulfilled although I am throwing an error
handleFetchErrors(response);
return (data.id);
} catch (e) {
console.error(e);
}
})
In my createSlice
I am using these extraReducers for the upper case
.addCase(deleteApplication.fulfilled, (state, action) => {
state.status = DataFetchingStatus.succeeded
state.applications = state.applications.filter(application => application.id !== action.payload)
})
.addCase(deleteApplication.rejected, (state, action) => {
state.status = DataFetchingStatus.failed
state.error = action.payload
})
The deleteApplication.fulfilled
is getting triggered instead of the deleteApplication.rejected
.
Am I missing something?
The handleFetchErrors
function throws an error, but this error is caught by deleteApplication
and merely printed as a console message. Hence, deleteApplication.rejected
is never dispatched. I suggest either (a) not catching the error; or (b) re-throwing the error in the catch block.