1

I have a button on click of which i am navigating to the other component

<Link to="/result"><button onClick = {this.setDealSizeAndType} name="patient">Calculate</button></Link>

  setDealSizeAndType({ target }){

    const dealTypeName = target.name ;
    this.setState({
      dealType: dealTypeName
    }, function(){
        this.props.setDealType(this.state.dealType);
    });
  }

function mapDispatchToProps(dispatch){
  return {
    setDealType: (dealType) =>{
      dispatch(setType(dealType));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Calculator);

But the state is not getting set. I am getting undefined. I have to get this value in my next component which is not related to this component. Is there any way , i can set the state , before rendering of next component.

Atul kumar singh
  • 402
  • 5
  • 21

2 Answers2

1

You can use bind function when calling the onclick handler, so here goes the updated code

<Link to="/result"><button onClick = {this.setDealSizeAndType.bind(this,'patient')}>Calculate</button></Link>

Now in the function setDealSizeAndType, you will directly receive the name.

 setDealSizeAndType(name){

const dealTypeName = name ;
this.setState({
  dealType: dealTypeName
}, function(){
    this.props.setDealType(this.state.dealType);
});
}

Hope this helps

mindaJalaj
  • 428
  • 3
  • 11
1

Instead of using a link, you can dynamically navigate

<button onClick = {this.setDealSizeAndType} name="patient">Calculate</button>

  setDealSizeAndType({ target }){

    const dealTypeName = target.name ;
    this.setState({
      dealType: dealTypeName
    }, function(){
        this.props.setDealType(this.state.dealType);
        this.props.history.push('/result');  // Programmatically navigate like this
    });
  }

function mapDispatchToProps(dispatch){
  return {
    setDealType: (dealType) =>{
      dispatch(setType(dealType));
    }
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Calculator));

You can check this answer on How to Programmatically navigate using react router

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318