I'm new to redux, and I'm rebuilding a fairly complex reactjs app using redux.
I thought it made sense to build a "feature" for notifications that would have a slice of state with like
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
export interface NotificationState {
show: boolean,
status: 'info' | 'warn' | 'error' | 'success',
title: string,
message: string,
position: 'dash' | 'popover',
}
const initialState: NotificationState = {
show: false,
status: 'info',
title: '',
message: '',
position: 'popover',
};
export const notificationSlice = createSlice({
name: 'notification',
initialState,
reducers: {
show: (state, action: PayloadAction<NotificationState>) => {
state = action.payload;
},
hide: (state) => {
state.show = false;
},
toggle: (state) => {
state.show = !state.show;
},
},
});
const { actions, reducer } = notificationSlice;
export const { show, hide, toggle } = actions;
export const selectNotification = (state: RootState) => state.notification;
export default reducer;
that would control how the notice shows, what position, what alert colors are used, etc.
However, now that I'm getting down to the implementation, I'm finding that I want to show notifications based on other features' state. For example, in my blog-posts
feature, I fetch data from the server via a thunk
and I'd like to set a notification based on the state of the thunk:
extraReducers: (builder) => {
builder
.addCase(fetchBlogPosts.fulfilled, (state, action) => {
state.status = 'idle';
state.entities = action.payload;
})
// hopefully this will apply to any failed / pending request
.addMatcher(isRejectedAction, (state, action) => {
state.error = action.error;
// store.dispatch(show({
// show: true,
// status: 'error',
// title: 'Request Failed',
// message: action.error.message,
// position: 'popover',
// autoHide: false,
// confirm: false,
// }));
})
.addMatcher(isPendingAction, (state, action) => {
state.status = 'loading';
})
}
The obvious problem is that you're not supposed to dispatch action from reducers. Is this just a bad idea in general, or is there a way to set the notification
state from a thunk response? Is there a "best practices" way to deal with this?