I am building a notification system using Redux Toolkit and I am running into an issue. Here I want to trigger the showNotification when certain actions/reducers in other slices are called. So I have added extraReducer to my NotificationSlice. When I call dispatch(showNotification(type, message, duration)) from a component it goes through prepare callback and then the reducer as expected. However, when I call showNotification from the extraReducer case for handleLogInFailure() I see that it hits the prepare callback, but it never hits the reducer.
I tried changing the showNotification implementation in the extra reducer to use caseReducers:
However, this seems to bypass the prepare callback, which would then force me to call it with a full action (below) which is more verbose than I want if I have to have over 100 different extraReducers:
const { showNotification } = notificationSlice.caseReducers;
showNotification(state, {type: 'notification/handleLoginFailure', payload: { type, message, durations }});
What is the correct way to do this?
Current Implementation:
const notificationSlice = createSlice({
name: 'notification',
initialState: initialState,
reducers: {
showNotification: {
reducer(
state: NotificationState,
action: PayloadAction<{ type: NotificationType; message: string; duration?: number }>
) {
console.log('showNotification: REDUCE', action)
const { type, message, duration } = action.payload;
state.notifications.push(buildNotification(type, message, duration));
},
prepare(type: NotificationType, message: string, duration?: number) {
console.log('showNotification: PREPARE', {type, message, duration})
return {
payload: {
type,
message,
duration,
},
};
}, },
},
extraReducers: (builder) => {
builder.addCase(handleLogInFailure, (state, action: PayloadAction<string>) => {
const error = action.payload;
console.log('Notifications: handleLogInFailure', action)
showNotification('error', error)
});
},
I was expecting that calling the reducer from the extraReducer (w/o using the caseReducers pattern) would properly go through the prepare callback and then go to the reducer.