I've got an authSlice
const authSlice = createSlice({
name: 'authStore',
initialState,
reducers: {
logout(state = initialState) {
return { ...state, isAuthenticated: false };
},
},
extraReducers: (builder) => {
builder.addCase(login.fulfilled, (state, { payload }) => {
state.isAuthenticated = true;
localStorage.setItem('userId', payload.userId);
});
builder.addCase(login.pending, (state) => {
state.isLoading = true;
});
builder.addCase(login.rejected, (state, { payload, error }) => {
if (payload) {
state.loginError = payload;
state.isLoading = false;
} else {
state.loginError = error;
}
});
},
});
and a userSlice
:
const userSlice = createSlice({
name: 'userStore',
initialState,
reducers: {
clearUser(state = initialState) {
return { ...state };
},
},
extraReducers: (builder) => {
builder.addCase(getUser.fulfilled, (state, { payload }) => {
state.user = payload;
state.isLoading = false;
});
builder.addCase(getUser.pending, (state) => {
state.isLoading = true;
});
builder.addCase(getUser.rejected, (state) => {
state.isLoading = false;
});
},
});
I have a few questions about my code:
- How can I call
clearUser()
inuserSlice
fromauthSlice
? - Is this good practice or an anti-pattern?
- If it's an anti-pattern what is an alternative approach to doing this whilst keeping the separation of the
authSlice
and theuserSlice
?