0

I want to make a boolean true on the click of a button, but it shows "undefined" on console.log

export default class productdetail extends Component {
   constructor(props){
    super(props);
    this.state = {
        showCartMessage:false ,
    }
    this.handleCartListener = this.handleCartListener.bind(this);
   
   }
    handleCartListener(){
    this.setState({ showCartMessage: true });
    console.log(this.showCartMessage)
    }
    actionForProducts(product) {
      return(
         <div className="">
            <button className="add_cart btn  rounded-pill w-100  " onClick= 
                 {this.handleCartListener}>
            Add To Cart
           </button>
        </div>
      )
    }
    render(){
       return(
          <div className="p-3 h-100 ">
             {this.actionForProducts(this.props.productdetail)}
        </div>
       )
    }
}

How to resolve this? I tried so many times but it gives the same response.

5 Answers 5

1

showCardMessage is a property of the state variable. Not the class instance.

 console.log(this.state.showCartMessage)
Sign up to request clarification or add additional context in comments.

Comments

0

The state has been updated properly. you have to just use this.state.showCartMessage, to see the changes.

you can use callback function to check the state after updating.

handleCartListener(){
 this.setState({ showCartMessage: true }, ()=>{console.log(this.state.showCartMessage) });
}

Comments

0

If you want to put console.log to check the new value of state. You should put it into render() because the state only has a new value when component re-render

render(){
  console.log(this.state.showCartMessage)
}

1 Comment

it s work for me but in first click this give me false in console then give true
0

try to work with async await i had the same probleme the value is updated but the console.log show undefined until the next click it shows the previous state. Try this :

 async handleCartListener(){
    await this.setState({ showCartMessage: true });
    console.log(this.showCartMessage)
    }

Comments

0

you should use callback setState

handleCartListener(){
    this.setState({ showCartMessage: true },()=>{
    console.log(this.state.showCartMessage)
});
    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.