0

I am working with react reducer and came across one scenario and would like to know the better way to handle. I have array of object list and i would like to modify one of the object from list in reducer. As per the standard we should not mutate the state. I have the following example:

const state =
{
  items : [
    {
      'id': 1,
      'name': 'test1',
      'price': 10,
      'work': {
        'work1': 1
      }
    },
    {
      'id': 2,
      'name': 'test2',
      price: 20
    },
    {
      'id': 3,
      'name': 'test3',
      price: 30
    }
  ]
};
// here I would like to find item with id = 1 and modify that object with price = 40 and add new property into nested work property.
const test = state.items.map(item => {
  if (item.id ===1) {
    let newItem = {...item};
    newItem['price'] = 40;
    newItem['work'] = {...newItem['work'], 'work2': 2}
    return newItem;
  }
  return item;
})

I have checked the original state object and the new object after computation and found that state object is not being mutate. I would like to know, is this the right approach to work with array of object list with reducer or is there any other standard way to do this.

I would like to thanks in advance.

2 Answers 2

1

This is the expected behavior that the state doesn't change because when you use Array.map it copies every element instead of making a reference so the initial object isn't changed after map and you have to:

const newItems = state.items.map(item => {
  if (item.id ===1) {
    let newItem = {...item};
    newItem['price'] = 40;
    newItem['work'] = {...newItem['work'], 'work2': 2}
    return newItem;
  }
  return item;
})
this.setState({items: newItems })
Sign up to request clarification or add additional context in comments.

Comments

0

Your approach is correct, as you create a copy of the object before doing the changes on that object. However, with ES6 you can go a bit further with destructuring to make it a bit cleaner. I would approach it the following way:

const test = state.items.map(item =>
    item.id === 1
        ? ({
            ...item,
            price = 40,
            work: {
              ...item.work,
              work2: 2
            }
        })
        : item
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.