0

I am using Angular 2+ with Redux and is fine, but can not modify quantity with the new value

The error is: TypeError: Cannot assign to read only property 'quantity' of object '[object Object]'

export interface CartState {
    readonly cars: CartCarModel[]
  }

  export class CartCarModel {
    constructor (
      public carId: string,
      public carModel: string,
      public quantity: number,
      public price: number) { }
  }


  const initialState: CartState = {
    cars: []
  }

  function reducerFunc (state: CartState, id: string, quantity: number) {
    const nextState = produce(state, draft => {
    draft.cars.find(d => d.carId === id).quantity = quantity
  })

  return Object.assign({}, state, {
    drinks: nextState
  })
}

1 Answers1

0

because in redux you can't modify the value of the state u have to copy the values so use map instead of find and i hope things gose well

  • The same error TypeError: Cannot assign to read only property 'quantity' of object '[object Object]' ``` function reducerFunc(state: CartState, id: string, quantity: number) { const nextState = produce(state, draft => { draft.cars.map( ops => { if (ops.carId === id) { return ops.quantity = quantity; } else { return ops} }) }) return Object.assign({}, state, { cars: nextState }) }``` – user15242670 Feb 19 '21 at 13:17
  • because u still editing the same reference u have to clone the object and make return like that ``` if(ops.carld===id) return {...ops,quantity:quantity} else return ops ``` – Ahmäd LP SN Feb 19 '21 at 15:34
  • i just test it but not working, no error and the quentity is the same if (ops.drinkId === id) { return {...ops, quantity: quantity} } I am debuging with chrome and quentity is the same – user15242670 Feb 19 '21 at 15:47
  • i already checked out ur implementation so i found that u set readonly cars: CartCarModel[] try to remove readonly keyword – Ahmäd LP SN Feb 19 '21 at 16:02
  • https://blog.ng-book.com/introduction-to-redux-with-typescript-and-angular-2/ check this out ... there is no readonly keyword – Ahmäd LP SN Feb 19 '21 at 16:02
  • i believe that u has somethings wrong with ur Redux implementation please check out the Tutorial that i give u in the previous comment and let me know if u can't fix it – Ahmäd LP SN Feb 20 '21 at 01:44
  • its all about ngrx version I downgraded and everything is fine It was an amazing adventure :) – user15242670 Feb 20 '21 at 07:28