ibrahim
ibrahim

Reputation: 145

check if state is true or false react

I want to check If state is true or false if true I will send data to modal so I want to execute a function after setState is finished updating this is my code :

getPriceData = () => {
    if(this.state.visibleModal){
    const id = this.props.product._id;
    DataController.getProduct(id).then(
        response =>
        this.setState({
            product: response,
            buyingPrice: response.price
        })
    );
    }        
}


<Button title='ADD TO CART' id={_id}
    buttonStyle={{ backgroundColor: 'darkgreen', marginRight: 10 }}
    containerStyle={{ width: 120}}
    onPress={this._toggleModal&&this.getPriceData}/>

Upvotes: 2

Views: 2297

Answers (3)

Graphics Factory
Graphics Factory

Reputation: 246

You can also check like this...

if (checkState) {

//execute code if true

}

Upvotes: 0

thortsx
thortsx

Reputation: 2280

this.setState in React is asynchronous. So you can define one callback function in setState to handle like:

this.setState({
    product: response,
    buyingPrice: response.price
}, () => {
    // here, your state updated
    console.log('state updated: ', this.state)

})

Upvotes: 1

sallf
sallf

Reputation: 2868

You can try using componentDidUpdate().

componentDidUpdate(prevProps, prevState) {
  if (!prevState.visibleModal && this.state.visibleModal) {
    this.getPriceData();
  }
}

getPriceData = () => {
  const id = this.props.product._id;
  DataController.getProduct(id).then(
      response =>
      this.setState({
          product: response,
          buyingPrice: response.price
      })
  );      
}

...

<Button 
  title='ADD TO CART' 
  id={_id}
  buttonStyle={{ backgroundColor: 'darkgreen', marginRight: 10 }}
  containerStyle={{ width: 120}}
  onPress={this._toggleModal}
/>

Upvotes: 0

Related Questions