0

How do you update a certain nested property in redux state?

Let's say I only want to update the "value" property in the object below. I know you shouldn't deep copy the previous state but how do i only change the property of an object in an array in an object of an array?

Thanks in advance!

market {
  shops: [
    {
      name: 'abc',
      items: [
        {
          name: 'item1',
          value: 40,
          id: '234rfds32'
        },
        {}
      ]
    },
    {},
    {}
  ]
}

Something like the following:

state = {
  ...state, 
  shops: [
    ...state.shops,
    shops[index].items = [
      ...shops[index].items,
    ]
  ]
};

2
  • 1
    market.shops[0].items[0].value = 10 is this what you are looking for? Commented Aug 22, 2018 at 9:10
  • @AnkitAgarwal Thanks for the fast reply but no, i updated the post to make it more clear what I'm looking for. I want to update the state with only the "value" property changed. Commented Aug 22, 2018 at 9:20

1 Answer 1

1

Something like this would work. (code looks ugly, didn't test though)

var shop =  state.shops[index];
var items = [...shop.items];
items[<index>].value = 'your value';
shop.items = items;
var shops = [...state.shops];
shops[index] = shop;

state = {
...state, 
shops 
};
Sign up to request clarification or add additional context in comments.

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.