Home > Software engineering >  How do I reset the Redux State using createSlice?
How do I reset the Redux State using createSlice?

Time:01-11

I'm trying to reset my Redux state for the user when the user logs out and here is my code:

export interface UserInterface {
    id: string | null;
    name: string | null;
    email: string | null;
    notes: Array<string>
    seq: number | null
}

export interface UserState {
    user: UserInterface
}

const initialState: UserState = {
    user: {
        id: null,
        name: null,
        email: null,
        notes: [],
        seq: null,
    },
}

export const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {
        setUser: (state, action: PayloadAction<UserInterface>) => {
            state.user = action.payload
        },
        removeUser: (state) => {
            state.user = {
                id: null,
                name: null,
                email: null,
                notes: [],
                seq: null,
            }
        },
    }
});

I was thinking of executing the removeUser reducer without any sort or argument since I'm just reseting the state when the user logs out. If I executed it as: dispatch(removeUser()) will this be correct?

CodePudding user response:

Yes, it's proper use. And additional you can rewrite action removeUser like

removeUser: (state) => {
  return initialState
}
  • Related