0

I have a print function, it first sets the state of isPrinting to true and open a pring dialog. Once the dialog is being closed it sets the state of isPrinting to false and at this point I'm getting the error (second setState):

Uncaught ReferenceError: setState is not defined

I binded function to current context with the arrow function.

  handlePrint = () => {
    this.setState({ isPrinting: true }, () => { //setState is working working properly
      window.print();
      if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener = (mql) => {
          if (!mql.matches) {
            this.setState({ isPrinting: false }); //Error
          }
        }
      }
    });
  };
user3378165
  • 6,546
  • 17
  • 62
  • 101

5 Answers5

1

Try this.

handlePrint = () => {
let _this = this;
this.setState({ isPrinting: true }, () => {
  window.print();
  if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener = (mql) => {
      if (!mql.matches) {
        _this.setState({ isPrinting: false });
      }
    }
  }
});
};
Prabu samvel
  • 1,213
  • 8
  • 19
1

I am not sure what you are trying to achieve here but the window.print() freezes the app. There is no code being run unless someone clicks the printing screen away. I works just like window.alert("..."). You can try that by printing a thimestamp right after the win.print. So besides that there is a problem with the this context that cannot be reached the whole function is useless. Because you could just do:

  handlePrint = () => {
    this.setState({ isPrinting: true }, () => {
      window.print() //freezes until someone clicks it away.
      this.setState({ isPrinting: false }) //Error
    })
  }

Regards

Bob Senrie
  • 47
  • 1
  • 1
  • 6
0

At the second time, instead of setState, just return the new state like:

return {
  isPrinting: false,
};
Amol B Jamkar
  • 1,227
  • 10
  • 19
Joan
  • 68
  • 5
0

This should help

  handlePrint = () => {
    this.setState({ isPrinting: true }, () => { //setState is working working properly
      window.print();
      if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener = (mql) => {
          if (!mql.matches) {
            return { isPrinting: false };
          }
        }
      }
    });
  };

setState method should return a new state rather than try to execute anything.

-1

How did you use the function 'mediaQueryList.addListener'?You can console the two 'this' and see if they are same.

Jack
  • 46
  • 2