Search code examples
reduxredux-toolkit

Why my Redux App return that [ Immer ] error?


I don't know. Why even I added my push function on my object to return my new result, The app is printing error on my console.log.

slice.js

import { createSlice } from '@reduxjs/toolkit';
import { pushProduct } from '../commons/push';

export const slice = createSlice({
    name: 'initial',
    
    initialState : {
        product: [],
    },
    
    reducers: {
        ADDS(state, actions) {
            return {
                ...state, 
                product: pushProduct(state.product, actions.payload),
                console1: console.log('State: ', state.product),
                console2: console.log('Actions: ', actions.payload),
            } 
        }
    }
});

export const { ADDS } = slice.actions;

export default slice.reducer;

push.js

// Push new prpduct to the cart
export const pushProduct = (initial, productSelect) => { return initial.push(productSelect) };

console.log error

errors.ts:49 Uncaught Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.

Thank You


Solution

  • Per the error message: Immer lets you update the state in two ways. One is "mutating" the existing state, and the other is returning a new value. But, you can only do one of those at a time.

    You're trying to do both. You have return {...state}, but you also have pushProduct() which sounds like it's mutating.

    The best answer here is to not try to do return {...state} at all, and just "mutate" the existing state.

    See https://redux-toolkit.js.org/usage/immer-reducers#mutating-and-returning-state for more details.