Reputation: 13
Currently I am using createReducer (https://redux-toolkit.js.org/api/createreducer), but now I am looking forward to convert it into switch case reducer (https://redux.js.org/usage/structuring-reducers/refactoring-reducer-example). I've tried to convert it, but somehow things are going wrong and I am not sure what's the correct way to handle nested object through switch case reducer
My code with createReducer
export let sampleReducer = createReducer(initialState, {
[ACTIONS.ADD_USER]: (state, action) => {
if (state.user[action.info]) {
state.user[action.info].details = action.details;
}
}
});
export default sampleReducer;
Above code is working fine, but when i convert it into switch case, I am not getting the expected response.
New code
export const sampleReducer = (
state: sampleState = initialState,
action
) => {
switch (action.type) {
case ACTIONS.ADD_USER:
if (state.user[action.info]) {
return {
...state
user: {
[action.info]: {
details: action.details
}
},
};
}
default:
return state;
}
};
export default sampleReducer;
Please let me know if new way of writing reducer is correct or not.
Upvotes: 0
Views: 1077
Reputation: 67587
Please don't do this! We want people to use RTK's APIs, and not switch-case functions!
In fact, you shouldn't even be using createReducer
in most cases. The "right" answer here is to use RTK's createSlice
API, which will generate the action creators and action types for you:
const sampleSlice = createSlice({
name: 'sample'
initialState,
reducers: {
userAdded: (state, action) => {
if (state.user[action.info]) {
state.user[action.info].details = action.details;
}
}
}
});
export const { userAdded } = sampleSlice.actions;
export default sampleSlice.reducer;
Some of our docs pages are older and haven't been updated to show the latest APIs and patterns, but you should be using RTK for everything.
Additionally, the concepts shown in pages like the "Structuring Reducers" section are valid no matter how you actually write the code.
Upvotes: 1