I am using redux toolkit for app state management. I created 4 slices in it and I want to clear all the slices when user click logout button.
I know we can dispatch 4 methods to clear each slice, but is there a way that can clear the whole store.
I am using redux toolkit for app state management. I created 4 slices in it and I want to clear all the slices when user click logout button.
I know we can dispatch 4 methods to clear each slice, but is there a way that can clear the whole store.
You can use the same action across multiple reducers with the extraReducers
field in createSlice
.
https://redux-toolkit.js.org/api/createSlice
The following code example creates that action using createAction
(but it could also be created by one of the four code slices).
const clearAction = createAction('clear');
const initialStateForSlice1 = { /* etc */ };
const slice1 = createSlice({
initialState: initialStateForSlice1,
reducers: { /* etc */ },
extraReducers: (builder) => {
builder.addCase(clearAction, () => initialStateForSlice1);
}
});
const initialStateForSlice2 = { /* etc */ };
const slice2 = createSlice({
initialState: initialStateForSlice2,
reducers: { /* etc */ },
extraReducers: (builder) => {
builder.addCase(clearAction, () => initialStateForSlice2);
}
});
// and so on for each slice