Search code examples
reactjssetstate

React-to-print: how to change state in onAfterPrint when closing print window


I am using react-to-print library, and using that, I want to change a state when closing print window.

When I click cancel button, it works fine. However, if I click X (exit) button, it will crash.

I have the following code.

<ReactToPrint
  trigger={() => (
    ...
  )}
  content={() => ...}
  onBeforePrint={() => { this.setState({ printState: true}) }}
  onAfterPrint={() => { this.setState({ printState: false }) }}  
  closeAfterPrint
/>

Here's the error message

Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.


Solution

  • It might not be it, but try using onAfterPrint={() => this.handlePrintAfter()}