Throw error on rejection
See original GitHub issueHi, I’m migrating my application from redux-thunk + redux-promise-middleware to redux-toolkit.
I have a problem that I cannot solve that concerns throwing the error in an asynchronous action.
The main difference with redux-promise-middleware is that if an error is generated in an asynchronous action, it dispatches the failed action and at the same time does not stop the error throw. On the redux-toolkit instead the action is only rejected. Reading the various issues on redux-toolkit, I deduced that adding the serializeError option and throwing the error, I did also receive the error on the dispatch of the action, however the reject action is not performed.
I’m going to write some code to explain the context:
class PostContainer extends React.Component {
public componentDidMount() {
try {
this.props.preload();
} catch(err) {
console.log(err);
// i'd like to receive here the error
}
}
}
const mapDispatchToProps = (dispatch: any) => ({
preload() {
await dispatch(preload());
dispatch(somethingelse())
}
});
export default connect(null, mapDispatchToProps)(PostContainer);
// action
const preload = createAsyncThunk('post/preload', async (_: void, { dispatch }) => {
// if one of this two action throw an error
await dispatch(getPosts());
await dispatch(getUsers());
});
expost const postSlice = createSlice({
name: 'post',
initialState,
reducers: {},
extraReducers: (builder) => {
// i'd like to receive the rejected action
builder.addCase(prealod.rejected, (state, action) => {
return {
...state,
isError: true
}
})
}
})
Is there a way to achieve this with redux-toolkit?
Maybe should i use the unwrapResult
utility?
If this is the case, how can i implement in this scenario?
Thanks for you time.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:8 (1 by maintainers)
Thank you for that input. I agree that would be an unwanted case to have to add to RTK.
I did find a solution that restores my expected use case of 1) throwing errors by default after dispatching rejections and 2) ignoring
ConditionError
–appending this middleware after the RTK default middleware:With this in place, I no longer need to
.then(unwrapResult)
everywhere which, in turn, ignoresConditionError
s.Agreed that it’s not terribly pretty if you have to add that in a bunch of spots.
FWIW, these threads have prior discussion on the topic: #734, #775 , and #792 . In particular, #792 has a lot of design discussion related to this, such as https://github.com/reduxjs/redux-toolkit/pull/792#issuecomment-722710316 .