Ata Mohammadi
Ata Mohammadi

Reputation: 3550

React-Native: State is changed, but returning old value

I have two components. There is a button on ComponentA, when you click on it, it changes the state:

import ComponentB from './ComponentB'
.
.
constructor(props) {
    super(props);
    this.state = {
        filter: true,
    };
}
.
.
.
<TouchableOpacity
    onPress={()=>{ this.setState({filter: !this.state.filter }); }}
>
    {this.state.filter ?
        <Text>Enabled</Text> :
        <Text>Disabled</Text>
    }
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />

ComponentB

render(){
    return(
      <View><Text>{this.props.filter}</Text></View>
    );
}

Funny thing is, when you click on the button, the state does change and the text which is based on the state will also change. So at first time it changes from True to False. But ComponentB will receive still True instead of False. When you click on it again, state changes from False to True, the text is also being shown correctly, but this time ComponentB will receive True instead of False. Am I passing props to ComponentB wrong? Am I missing something?

Thanks in advance.

Upvotes: 0

Views: 3400

Answers (3)

atif
atif

Reputation: 769

ComponentB

state = {
 filter: this.props.filter
}

componentWillReceiveProps(nextProps) {
 if(this.props.filter !== nextProps.filter){
   this.setState({
     filter: nextProps.filter
   })
 }
}

render(){
 return(
  <Text>{this.state.filter}</Text>
 );
}

this might solve your issue of props not updating when parent state gets changed.

Upvotes: 1

Santosh Sharma
Santosh Sharma

Reputation: 2248

You need To pass state in on onPress

like

import ComponentB from './ComponentB'
.
.
constructor(props) {
    super(props);
    this.state = {
        filter: true,
    };
}
changeFilter = (filter) => { this.setState({filter: !filter }); };
.
.
.
<TouchableOpacity
    onPress={()=> this.changeFilter(this.state.filter); }
>
    {this.state.filter ?
        <Text>Enabled</Text> :
        <Text>Disabled</Text>
    }
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />

Upvotes: 2

J. Mark Stevens
J. Mark Stevens

Reputation: 4945

Move your setState out of the view;

import ComponentB from './ComponentB'
.
.
constructor(props) {
    super(props);
    this.state = {
        filter: true,
    };
}
changeFilter = () => { this.setState({filter: !this.state.filter }); };
.
.
.
<TouchableOpacity
    onPress={()=> this.changeFilter(); }
>
    {this.state.filter ?
        <Text>Enabled</Text> :
        <Text>Disabled</Text>
    }
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />

Upvotes: 2

Related Questions