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 
  }
})
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • I think React is not designed to work with dynamic fields. Why must you use dynamic fields? Would you like to try alternatives? – DMaster Sep 14 '17 at 16:51

1 Answers1

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 });
nbkhope
  • 7,360
  • 4
  • 40
  • 58