Reputation: 896
I am fetching some rows via an API and assigning the state variables like this
this.setState({
rows: data,
originalRows: data
})
Now I am using these state variables in a filter method where I change the number of rows based on filters.
let rows = this.state.rows
filterFunction(){
//filter logic, editing the variable rows
}
The issue is, this also changes the value of this.state.originalRows
How to avoid the change that state value?
Upvotes: 0
Views: 633
Reputation: 2368
Various ways to achieve this.
// rest-spread operator copies values to new object
const obj = {...this.state.originalRows}
// merges your values to an empty object which works same way
const obj2 = Object.assign({}, this.state.originalRows)
If you just write your code as following
const obj = this.state.originalRows
you just create reference
to an original variable eg. pointer and change values with in original variable.
Upvotes: 1