I'm receiving a state mutation error when using Immer's produce to manipulate the state.
When I create a test interface manually inside the same reducer and call produce, it seems to work as expected:
export interface ItemSliceState {
items: Array<IItem> | null | undefined;
}
export const initialState: ItemSliceState = { items: [] };
export const updateItem: CaseReducer<
ItemSliceState,
PayloadAction<IItem | null | undefined>
> = (state: ItemSliceState = initialState, action) => {
const testItem: IItem = {
status: 1
};
const testItems: Array<IItems> = [testItem];
const testState: ItemSliceState = { items: testItems };
const nextTestState = produce(testState, draftState => {
if (!draftState || !draftState.items) {
return testState;
}
draftState.items[0].status = 2;
});
const nextState = produce(state, draftState => {
if (!draftState || !draftState.items) {
return state;
}
draftState.items[0].status = 2;
});
...
// testState.items[0].status = 1
// nextTestState.items[0].status = 2
// state.items[0].status = 2
// nextState.items[0].status = 2
Why is 'state' being manipulated, while 'testState' remains unchanged when produce is called in the same way?
Sandbox with state being updated correctly: https://codesandbox.io/embed/festive-ritchie-5nf31?fontsize=14&hidenavigation=1&theme=dark