user1354934
user1354934

Reputation: 8841

how to avoid mutating this.state or redux object

For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.

Is it bad practice to do this?

Object.keys(this.state).map(k => this.state[k]);

Thanks

Upvotes: 0

Views: 333

Answers (2)

kartikag01
kartikag01

Reputation: 1579

React Mutating State.

let state = {
    age    : 25,
    name   : 'Robin',
    friends: ['Barney', 'Ted']
}

Change Age

this.setState({age: 26}) 

Change Name

this.setState({name: 'Lily'}) 

Add Friend

this.setState({ 
    friends: this.state.friends.concat(['Marshall'])
})

Try this library immutability-helper for complex state updates.

Upvotes: 0

fubar
fubar

Reputation: 17398

In React, you should only mutate this.state using this.setState() so that React knows when to re-render components.

The line of code you've written is fine, because you're not actually modifying the state object. You've already created a new array using Object.keys.

If however, you want to copy this.state without modifying it, try the following.

const state = {...this.state};

// Or 

const state = Object.assign({}, this.state);

Upvotes: 2

Related Questions