0

I have piece of code,

this.setState({ generateGraphTableforPDF: true }, () => {
 this.generatePDFData(true);
 this.setState({ generateGraphTableforPDF: false });
});

This setstate callback executes before render finish so, in dom there is no table hence empty pdf is generated.

I tried to remove the callback function and wrote them in componentDidUpdate with settimeout 0. But the issue is this is also failing in some scenarios.

2 Answers2

0

In your code, the logic inside your callback-function does not run synchronously. this.generatePDFData(true) does not complete before executing this.setState({ generateGraphTableforPDF: false })

Your flow of logic should look something like this instead so all procedures are finished before executing the next step:

handleChangeOrWhateverFunction = () => {
    this.setState({
       generateGraphTableforPDF: true
    })
}

componentDidUpdate(prevProps, prevState){
   if(this.state.generateGraphTableforPDF && prevState.generateGraphTableforPDF !== this.state.generateGraphTableforPDF){
       this.generatePDFData(true)
   }
}

generatePDFData = (boolean) => {
...pdf generating logic
   this.setState({
      generateGraphTableforPDF: false
   })
}
Chris Ngo
  • 15,460
  • 3
  • 23
  • 46
  • Didnot work cz the table is created in render (using child component) after setState and its taking longer time and till then parent's componentDidUpdate is called. render () { {this.state.generateGraphTableforPDF ? ( ) : null}} However same code worked fine in react15 – user3152719 Jul 03 '19 at 05:17
0

You can do this,

this.setState({ generateGraphTableforPDF: true }, () => {
   this.generatePDFData(true);
});

function generatePDFData(bool){
   //Your logic to generate PDF
   this.setState({ generateGraphTableforPDF: false });
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59