tschaka1904
tschaka1904

Reputation: 1489

Partial reset of state with createSlice

I'm having an action, which is supposed to do a partial reset on some state properties.

Before moving over to the redux-toolkit, I have achieved this with the following code:

initialState

const initialState = {
    username: null,
    dateOfBirth: null,
    homeTown: null,
    address: null,
    postCode: null,
    floor: null,
}

reducer

switch (action.type) {
    ...
    case USER_SET_HOME_TOWN:
        return {
            ...initialState,
            homeTown: action.payload
            username: state.userName,
            dateOfBirth: state.dateOfBirth,
        };
    ...
    default:
      return state;
}

USER_SET_HOME_TOWN is dispatched every time homeTown is changing and maintains the username and the dateOfBirth, whilst resting everything else back to the initialState.

Now with the redux toolkit and createSlice I'm trying to achieve a similar behaviour by writing something like:

createSlice - not working

const user = createSlice({
    name: 'user',
    ...
    reducers: {
        ...
        userSetHomeTown: {
            reducer: (state, action) => {
                state = { ...initialState };
                state.homeTown = action.payload;
                state.username = state.payload;
                state.dateOfBirth = state.dateOfBirth;
            },
        },
        ...
    },
});

This isn't working, which, I guess, makes sense since state = { ...initialState}; resets the state and state.username/dateOfBirth: state.username/dateOfBirth; are kind of useless then and counter productive... or simply just wrong.

After changing this to:

createSlice - working

const user = createSlice({
    name: 'user',
    ...
    reducers: {
        ...
        userSetHomeTown: {
            reducer: (state, action) => ({
                ...initialState,
                homeTown: action.payload,
                username: state.payload,
                dateOfBirth: state.dateOfBirth,
            }),
        },
        ...
    },
});

It did work, but I'm still wondering if this is the recommended and right way of doing it.

Upvotes: 3

Views: 1037

Answers (1)

markerikson
markerikson

Reputation: 67539

Yes, that's correct.

Remember that Immer works by either mutating the existing state object (state.someField = someValue), or returning an entirely new value you constructed yourself immutably.

Just doing state = initialState is neither of those. All it does is point the local variable state to a different reference.

The other option here would be Object.assign(state, initialState), which would overwrite the fields in state and thus mutate it.

Upvotes: 4

Related Questions