-1
this.state = {
   old: null,
   new: null
}

componentDidMount() {
  // get data
  this.setState({old: data, new: data})
}

updateData() {
  // some code
  this.setState({new: newData})
}

Above code updates both old and new inside updateData() what i want is to get data and store in 2 different variable (old & new), update new with user input and compare/send to server etc..

EDIT: Input change part

<label for="pname">
  Min: {this.state.old.parameters[i][1]}
</label>
<input
  name={"p-" + item[0]}
  className="form-control"
  value={this.state.new.parameters[i][1]}
  onChange={e => this.handleChange(e, i, 1)}
/>

Handle Change:

handleChange(e, i, x) {
  let temp = this.state.new;
  temp.parameters[i][x] = e.target.value;
  this.setState({ new: temp });
}

EDIT: Here is a simple example to describe my issue. When you change first input all other inputs are also changing where they shouldn't

codesandbox

ggnoredo
  • 801
  • 1
  • 13
  • 33
  • That code doesn't do what you describe. Please show an example that replicates the problem ([mcve]). Best guess is that `data` is an object or an array and you change the elements directly instead of cloning it first. – Guy Incognito Jun 22 '20 at 07:17
  • that's it, i mean it updates both states even i only put `new` inside setState function – ggnoredo Jun 22 '20 at 07:21
  • That's not it. The problem is somewhere else. – Guy Incognito Jun 22 '20 at 07:21
  • Like I suspected, when you do `let temp = this.state.new` and then change `temp`, it changes the original `this.state.new` which is the same as `this.state.old`. You need to do `let temp = { ...this.state.new }` to clone the object so changing it won't change the original. – Guy Incognito Jun 22 '20 at 07:32
  • @GuyIncognito still same, it changes `old` even though there is no statement to do that – ggnoredo Jun 22 '20 at 07:40
  • And you have to do the same to all nested objects. See https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Guy Incognito Jun 22 '20 at 07:42

1 Answers1

0

Upon setState call, the original contents have to be retained too, which can be done by using {...this.state,//and any parameter changes(such as new:newData etc)}. Also, the issue was regarding Shallow and Deep copying of objects in js. Assigning objects, for example - let temp={...this.state.new} makes Shallow copy of the object and the both references point to the same object! I have made necessary changes, hope it works!

Handle Change :

handleChange(e, i, x){
    let temp = JSON.parse(JSON.stringify(this.state));
    temp.new.parameters[i][x] = e.target.value;
    this.setState({...this.state, new: temp.new});
};

Update Data function call :

updateData(){
    // some code
    this.setState({...this.state, new: newData});
}
Sagar Kulkarni
  • 483
  • 4
  • 15