D
D
DeniSidorenko2020-11-10 09:26:42
React
DeniSidorenko, 2020-11-10 09:26:42

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
  }
}


Most of all I want to draw attention to this moment
if(existItem)
      {
        console.log(item) // Quantity = 1
        item.quantity += 1
        console.log(item) // Quantity =  2

        return{
          ...state,
          total: state.total + item.price,
        }
      }


I made a simple check that if asideItems already has one, then just change the quantity. As you can see from console.log - it works, but does not send to state. And why each value in the state itself does not change. Who can tell me what is wrong item.quantity += 1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolegs, 2020-11-10
@DeniSidorenko

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 question

Ask a Question

731 491 924 answers to any question