user3380358
user3380358

Reputation: 143

React state updates incorrectly

Expected: I am trying to access state data in a variable and manipulate the variable. and again I will setstate the maniplated date into setstate.

Issue: when I assign a a state to a variable, instead of just copying the data in the state it becomes duplicate of the state itself, hence when I manipulate the data state itself is changes.

Note: in the below code, tmpData.splice is where state changes when I change the tmpData variable.

onRowAdd: newData => new Promise(resolve => {
    setTimeout(() => {
        {
        const { data } = this.state;
        const tmpData = data;
        const tmpRowData = this.getRowData(this.state.valorenVal ? this.state.valorenVal : newData.nr ? newData.nr : '');
        if (tmpRowData.length >= 1) {
            if (newData.number && tmpRowData[0].nr) {
                tmpRowData[0].number = newData.number ? newData.number : '';

                tmpData.splice(tmpData.length, 0, tmpRowData[0]);

                this.setState({ data: tmpData }, () => resolve());
                this.setState({ valorenVal: '' });
            } else {
                this.setState({ data }, () => resolve());
            }
        } else {
            this.setState({ data }, () => resolve());
        }
        }
        resolve();
    }, 1000);
}),

I'm new to React, this may be a silly issue but your answer will help me understand React better.

Upvotes: 2

Views: 463

Answers (3)

user11081925
user11081925

Reputation:

React use shallow compare to check on whether the current props and nextProps objects as well as the current state and nextState objects are equal. It means if all keys in the state have the same value, React will never re-render the component.

In your code tmpData is equal to data, both of them are the index of the same Object.

function shallowEqual(state, nextState) {
    if ( state === nextState) {
        return true; 
    }

    return Object.keys(state).every(key => state[key] === nextState[key]);
}

Upvotes: 1

Chris B.
Chris B.

Reputation: 5763

In React, you need avoid direct state mutations, as it prevents React from accurately tracking the changes that occur. Assuming data is an array, you can create a copy of it like this:

const tmpData = [...data];

or

const tmpData = Array.from(data);

And edit it as much as you need without causing unwanted mutations before updating the state with setState

Upvotes: 2

Stephen Collins
Stephen Collins

Reputation: 903

tmpData is a shallow copy of data. Since the reference from tmpData is maintained from data via a shallow copy, that’s why you are still mutating data.

Try the following:

const tmpData = data.slice()

That creates a new array, that should break references to the original array, allowing you to do what you would like to create the next state of data. Hope it helps

Upvotes: 1

Related Questions