Rajesh
Rajesh

Reputation: 3778

React Native - Setting return value of function to a component's property not working

I am using the react native switch component and want to change the state of a switch (on/off) programmatically when state changes for another switch. Below is the code I have:

update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.state.somekey = !val;
    }
};

<Switch onValueChange={(v) => this.update('somekey', v)} value={this.state.somekey} />

<Switch onValueChange={(v) => this.update('togglekey', v)} value={this.state.togglekey} />

When I click on the togglekey switch, I am expecting the somekey switch to toggle on or off, but it is not working. Any pointers?

Upvotes: 1

Views: 598

Answers (1)

Moti Azu
Moti Azu

Reputation: 5442

You can't mutate state directly. You must use setState instead, only then will React acknowledge the state update.

update = (key: string, val: boolean) => {
    if(key == 'togglekey') {
        this.setState({somekey: !val});
    }
};

Upvotes: 1

Related Questions