0

I need to update state of a specific object field. My state is using a dynamic key value (index).

First I'm doing:

this.setState({
  [index]: {
    uploading: uploadInstance,
    progress: 0
  }
})

Now I need only to update the progress field. With my attempt the uploading field gets lost:

this.setState({ 
  [index]: { 
    progress: progress 
  }
})
1
  • I think React is not designed to work with dynamic fields. Why must you use dynamic fields? Would you like to try alternatives? Commented Sep 14, 2017 at 16:51

1 Answer 1

3

Make a copy of the object at this.state[index] and replace the progress property with a new one.

const updatedOne = { ...this.state[index], progress: someNewProgress };
this.setState({ [index]: updatedOne });

That way, the previous properties from the object will be preserved and the progress will be replaced with the new one.

If you don't have support for the spread operator, you can use Object.assign:

const updatedOne = Object.assign({}, this.state[index], { progress: someNewProgress });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.