So, I have a reducer which needs to update the state array. The state array is expected to be:
[{productId: number; quantity: number}, ...]
Here, I match the object id, if it exists already, I need to update the quantity but if not then I need to push the the entire object to the array. To achieve this, I've tried multiple things with map, filter etc. Pushing the 1st element in the state is always fine but to update the count or to add a new element, whatever I've tried so far doesnt gives state as array of objects, instead, its array of Proxy.
The object becomes this:
Proxy{
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true
[[Prototype]]: Object
}
Here's the latest try:
const initialState: CartProduct[] = [];
const updateCart = (state: CartProduct[], payload: CartProduct) => {
const tempState = [...state, payload];
console.log({ tempState });
return tempState;
export const countReducer = createSlice({
name: "cart",
initialState,
reducers: {
increaseQuantity: (state, action) => {
if (!state.length) {
return updateCart(state, action.payload);
}
const index = state.findIndex(
(item) => item.productId === action.payload.productId
);
const newState = state;
newState[index].quantity = newState[index].quantity + 1;
console.log(newState); //gives Proxy again
// updateCart(newState, action.payload); //gives proxy as object in array
},
},
});
What I tried before this:
increaseQuantity: (state, action) => {
if (!state.length) {
return updateCart(state, action.payload);
}
const newState = state.map((product) => {
if (product.productId === action.payload.productId) {
console.log("i increase count");
return { ...product, quantity: product.quantity + 1 };
}
return product
});
return updateCart(newState, action.payload);
},