0

I'have a ReactJS event handler that need to change an array item, where the array is stored in component state. My code:

handleColumnResize = (index, width) => {
    let formData = Object.assign({}, this.state.formData);
    let columns = Object.assign({}, this.state.formData.columns);

    columns[index].width = width;

    formData.columns = columns;

    this.setState({
        formData: formData
    });

    if (this.props.onDataChange) this.props.onDataChange(formData);
};

I'm getting the following error:

TypeError: Cannot assign to read only property 'width' of object '#<Object>'

At the line: columns[index].width = width;

What is the correct way to change the content of the state array item?

OBS: My question is different of this post because if envolves changing an specific array item, no adding itens to a new array.

Mendes
  • 17,489
  • 35
  • 150
  • 263
  • 1
    Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Hardik Modha Nov 12 '18 at 12:09
  • What does your state look like originally? Is it a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object instead of a regular object? – Tholle Nov 12 '18 at 12:12
  • It is a regular object. formData is my variable name... – Mendes Nov 12 '18 at 12:31
  • Can you show up your state, the error means you're missing the coloumns in your formData. Then you cant set them coloumn width right. Or make a console.log(columns) bevore your error with line "columns[index].width = width;" – episch Nov 12 '18 at 13:37

1 Answers1

0

Check this.state.formData.columns.You have point columns to this.state.formData.columns.The reason that you have this problem is that you want to change some properties in this.state.formData.columns.And you should debugger like this:

Object.getOwnPropertyDescriptor(columns[index],width) 

And check the writable property.

Root
  • 2,301
  • 1
  • 10
  • 14