A.S.J
A.S.J

Reputation: 637

ReactJS change value of nested state

I have a form in which inputs have an initial value (which is different for each input). I set the value by saving the data in a state array, like so:

 function createData(header, content) {
    id += 1;
    return {header, content, id};
 } 

class ExampleForm extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        data : [
            createData( Header1, Content1),
            createData( Header2, Content2),
            createData( Header3, Content3),
        ]
}

Once the user startes typing something into the input field, I need to change the value of the state in in question in the corresponding array, however, I'm having trouble correctly targeting said state.

This is what I'm currently doing:

handleInputChange = (value, target) => {

        const selectedArray = {...this.state.data[target]};
        selArray.header = value;
        this.setState(selArray);
    };

}

(Note: value is the new value, target is the index)

However, it doesn't work because when I console.log() the new value, it still returns the old value.

I also read several other questions on here (with the help of with I wrote the code for what I'm doing right now in the function that changes the value), however, that did not work. Other questions I read include React: Update nested state? , however, I could not figure out where they got getPersonsData() from, for instance. Does anyone know what I'm doing wrong in my current code? How do I fix it?

Upvotes: 2

Views: 577

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

Update the state like this:

handleInputChange = (value, target) => {
    const data = [...this.state.data];
    data[target].header = value;
    this.setState({ data });
};

To check the updated state value, use callback method, like this:

handleInputChange = (value, target) => {
    const data = [...this.state.data];
    data[target].header = value;
    this.setState(
        { data }, 
        () => console.log('updated state', this.state.data) 
    );
};

For more details about asyn behaviour of setState check this answer: Why calling setState method doesn't mutate the state immediately?

Upvotes: 1

Related Questions