How to create global Error slice in Redux toolkit which will be receiving error value from other slices?

Viewed 471

I'm using Redux Toolkit and I have several slices:

user: {
 profile: {}
 daysOff: {}
}
offers: {
 fetchedOffers: {}
 publishedOffer: {}
}
general: {}

Each of them has its own Async Thunks and as a result, each of them has its own error: "value" pair.

I'd like to somehow create a global Error slice, which will have errorMsg key where I could store error messages from other slices.

The idea is to handle all errors on UI from a single place. I will check Error global slice only, if it has some error message, I would display it to the user. When user clicks on a pop up or alert with the message, I will clear the errorMsg so it wouldn't display anymore until another thunk is dispatched.

I'm not sure whether this is an adequate logic but I believe it's ok, however, I have no idea how to create this global slice which will be able to get error from other slices.

The resulting state tree would look like this:

user: {
 profile: {}
 daysOff: {}
}
offers: {
 fetchedOffers: {}
 publishedOffer: {}
}
general: {}
error: {
 message: 'email or password is invalid' or 'incorrect filter parameters'...whatever the 
 message is
}

Can anybody suggest how can I do something like this, please?

1 Answers

Though I found the solution in some other question on Stackoverflow and that solution was suggest by Dan Abramov, I will quickly answer how I completed my task.

I missed one of the important points of redux. Redux state tree has the same action for each of the reducers/slices. In other words, you can get access to action from any reducer even if the action was dispatched from some other reducer. In my case I just made a check whether action.error === true and if yes, I'm adding msg to the error field.

Related