Reducer Nested Object Update #4367
-
I am reasonably certain I know the answer to this, but just thought I would check... I want to write a reducer that contains the following action: export const MySlice = createSlice({
name: 'sliced',
initialState,
reducers: {
recordValue: (state: SliceState, action: PayloadAction<{ foo: Bar }>) => {
state.parent = state.parent || {};
state.parent.foo = action.payload.foo;
}
}
}) But something is telling me that is wrong and that the action creator should be: recordValue: (state: SliceState, action: PayloadAction<{ foo: Bar }>) => {
state.parent = { ...state.parent };
state.parent.foo = action.payload.foo;
} Or maybe it doesn't matter because Immer is able to detect the change any ways? If I added two selectors: selectors: {
SelectParent: (state: SliceState) => state.parent,
SelectFoo: (state: SliceState) => state.parent.foo
} Is there a difference when the selectors are triggered for updates? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It looks like that Personally, I'd write it as: if (!state.parent) {
state.parent = {}
} (Or if you really want to get fancy, the "nullish coalescing assignment operator": |
Beta Was this translation helpful? Give feedback.
It looks like that
state.parent =
line is just filling in a default value, right?Personally, I'd write it as:
(Or if you really want to get fancy, the "nullish coalescing assignment operator":
state.parent ??= {}
)