Ali
Ali

Reputation: 1207

react-native: How to setState() dynamic state in react-native?

I can create dynamic state like this example:

constructor(props) {
    super(props);
    this.state = {};
}

create state with this method:

func(name){
   this.state[name];
}

and setState with this:

func2(name,value){
   this.setState({[name]:value});
}

so with

this.func('color');
this.func('size');

I have this.func.color and this.func.size. right?

It works.

But I want something like this. I want create all new dynamic state in 'names' state.

constructor(props) {
        super(props);
        this.state = {names:[]};
}

names is a normal state.

func(name){
       this.state.names[name];
}

func2(name,value){
   this.setState({names:{[name]:value}:});
}

I call this functions:

func('color');
func('size');

func2('color','red');
func2('size','larg');

I expect with console.log(this.state.names) this:

{color:'red',size:'larg'}

But I get only {size:'larg'} (second function)

what is my wrong?

Upvotes: 0

Views: 264

Answers (1)

Clarence Leung
Clarence Leung

Reputation: 2556

You're overwriting the value of names when you call this.setState again.

You're effectively doing:

this.setState({ names: { color: 'red' }});
this.setState({ names: { size: 'large' }});

Consider using Object.assign() in func2 to make sure you're not replacing the object you're trying to add properties to.

func2(name,value) {
    this.setState({
        names: Object.assign(this.state.names, {[name]: value})
    });
}

Upvotes: 3

Related Questions