Answer the question
In order to leave comments, you need to log in
How to send a new quantity value to state?
Hello, I have this code
const initialState = {
asideItems: [],
total: 0
}
const asideReducer = (state = initialState, action) =>{
switch(action.type) {
case ADD_TO_ASIDE:
const item = action.payload
const existItem = state.asideItems.find(item => action.payload.id === item.id)
if(existItem)
{
console.log(item)
item.quantity += 1
console.log(item)
return{
...state,
total: state.total + item.price,
}
}
else{
return{
...state,
asideItems: [...state.asideItems , item],
total: state.total + item.price
}
}
default:
return state
}
}
if(existItem)
{
console.log(item) // Quantity = 1
item.quantity += 1
console.log(item) // Quantity = 2
return{
...state,
total: state.total + item.price,
}
}
item.quantity += 1
Answer the question
In order to leave comments, you need to log in
1. You are changing the object from payload, not from the state. You need to change existItem for something to change.
2. Redax assumes immutability. So the correct update of the state in this case will look like this:
const item = action.payload
const existItem = state.asideItems.find(item => action.payload.id === item.id);
if(existItem)
{
return{
...state,
asideItems: state.asideItems.map(currentItem => item.id === currentItem.id ? { ...currentItem, quantity: currentItem.quantity + 1 } : currentItem),
total: state.total + item.price,
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question