Reputation: 1
My code:
removeIndexCart: (state, action) => {
const IteamIndex_dec = state.cart.findIndex(
(iteam) => iteam.id === action.payload.id
);
if (state.cart[IteamIndex_dec].qnty >= 1) {
const dltiteams = (state.cart[IteamIndex_dec].qnty -= 1);
console.log([...state.cart, dltiteams]);
return {
...state,
cart: [...state.cart],
};
} else if (state.cart[IteamIndex_dec].qnty === 1) {
const data = state.cart.filter((el) => el.id !== action.payload);
return {
...state,
cart: data,
};
}
},
I wanted to reduce the selected products with index, but I encountered this error.
Upvotes: 0
Views: 63
Reputation: 7447
It seems that the reducer function is both trying to modify the proxy state
with Immer (automatically applied by redux-toolkit
), and returning a new value, which caused the error.
More about using redux-toolkit reducer with immer
Perhaps consider to always modify the proxy state
in the reducer (only works in redux-toolkit
where Immer is used internally), without returning a new value:
// Only works in redux-toolkit with immer
removeIndexCart: (state, action) => {
const IteamIndex_dec = state.cart.findIndex(
(iteam) => iteam.id === action.payload.id
);
if (state.cart[IteamIndex_dec].qnty > 1) {
state.cart[IteamIndex_dec].qnty -= 1;
} else if (state.cart[IteamIndex_dec].qnty === 1) {
state.cart = state.cart.filter((el) => el.id !== action.payload);
}
},
Alternatively, perhaps try always return a new value, without modifying the proxy state
:
removeIndexCart: (state, action) => {
const IteamIndex_dec = state.cart.findIndex(
(iteam) => iteam.id === action.payload.id
);
if (state.cart[IteamIndex_dec].qnty > 1) {
const updatedItem = {
...state.cart[IteamIndex_dec],
qnty: state.cart[IteamIndex_dec].qnty - 1,
};
const updatedCart = [...state.cart];
updatedCart[IteamIndex_dec] = updatedItem;
return {
...state,
cart: updatedCart,
};
} else if (state.cart[IteamIndex_dec].qnty === 1) {
const data = state.cart.filter((el) => el.id !== action.payload);
return {
...state,
cart: data,
};
}
},
Upvotes: 1