Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducer returns object instead of array

I have an odd problem with my reducer. It returns an object instead of array. How can I fix this?

export function reducer(state = {cart: []}, action) {
  switch (action.type) {
    case "ADD_TO_CART": {
      let oldState = [...state.cart]


      let index = oldState.findIndex(x => x.name === action.payload.name)


      return index > -1 ? {...state, cart: oldState} : {...state, cart: Object.assign({}, action.payload, {quantity: action.payload + 1 })} 


    }
    default: {
      return {
        ...state
      }
    }
  }
}

EDIT: For clarification I'm trying to add the action payload to the cart array if it doesn't exist and increment quantity and then just increment quantity if it does already exits in the cart array. State is supposed to be an object and cart is supposed to be an array. Cart seems to return an object when I expect an array.

P.S. I'm dangerous with ES6...

like image 565
Quesofat Avatar asked Jun 14 '26 14:06

Quesofat


1 Answers

The problem with your code is this line:

{...state, cart: Object.assign({}, action.payload, {quantity: action.payload + 1 })}

This is equivalent to this piece of procedural code:

const newCart =
  Object.assign({}, action.payload, {quantity: action.payload + 1 }

Object.assign({}, state, { cart: newCart });

Object.assign accepts any number of arguments as long as they all are all objects, then merges the properties of them, from right to left.

You expect the property cart in the returned object to be an array, while you are clearing assigning an object to it.

like image 66
ichigolas Avatar answered Jun 17 '26 03:06

ichigolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!