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.