RyanP13
RyanP13

Reputation: 7743

Update Object whose value is an array of objects in an immutable way

I need to update the state in my React component:

The state looks like this:

const state = {
    '123': [{
                progress: 0;
                lastModified: 999;
            },
            {
                progress: 0;
                lastModified: 666;
            }],
    '1234': [{
                progress: 0;
                lastModified: 111;
            },
            {
                progress: 0;
                lastModified: 222;
            }]            
};

Given that I know the object key e.g. 123 I want to update the progress value given that i also know the lastModified to use to find the object.

How to go about this in an immutable way?

Upvotes: 1

Views: 190

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You need to create new containers for all ancestors of the object you want to modify

const knownTarget = '123';
const knownLastModified = 666;
const changes = {
  progress: 100
}

const state = {
  '123': [{
      progress: 0,
      lastModified: 999,
    },
    {
      progress: 0,
      lastModified: 666,
    }
  ],
  '1234': [{
      progress: 0,
      lastModified: 111,
    },
    {
      progress: 0,
      lastModified: 222,
    }
  ]
};

const newState = { ...state,
  [knownTarget]: state[knownTarget].map(item => {
    if (item.lastModified === knownLastModified) {
      return {
        ...item,
        ...changes
      };
    }

    return item;
  })
}

console.log(state);
console.log(newState);

Upvotes: 1

Related Questions