What is the best to update state inside an array

Viewed 57

I have a code that loops through all the orders an updates the is_confirmed property to 1. The thing is I have to loop through all the orders find the one that matches the order id and update it.

My question is there more efficient way to do this without looping through all the objects?

export const orders = (state = [], action) => {
  const { type, payload } = action;

  switch (type) {
    case "NEW_ORDER":
      const { new_order } = payload;

      const new_state = state.concat(new_order);

      //console.log(new_state);

      return new_state;

    case "CONFIRM_ORDER":
      const { index } = payload;

      return state.map((order) => {
        if (order.id === index) {
          return { ...order, is_confirmed: 1 };
        } else {
          return state;
        }
      });
  }

  return state;
};
3 Answers

First of all, it would be best if you make your state an object

export const orders = (state = {orders : []},action)

And access your array as state.orders.

Next, never mutate a state variable, make a copy of it first

let ordersCopy= [...state.orders]

Then you can alter this array and set it to state:

ordersCopy.forEach((order) => {
                    if(order.id === index){
                        ordersCopy.splice(index,1,{...order, is_confirmed: 1})
                    } 
 return {...state, orders: ordersCopy}

And in your other case NEW_ORDER:

return {...state, orders: [...state.orders, new_order]}

I would just make a copy of the array and find the index of the matched element using findIndex. Then, update it using brackets to access the element:

case "CONFIRM_ORDER":
   const { index } = payload;

   const ordersCopy = [...state]
   const orderIndex = ordersCopy.findIndex(order => order.id === index)
   ordersCopy[orderIndex].is_confirmed = 1

   return ordersCopy
Related