1

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?

RyanP13
  • 7,413
  • 27
  • 96
  • 166

1 Answers1

1

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);
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317