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?

3

1 Answer 1

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);

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.