Search code examples
reactjsreload

ReactJs: How to Reload/refresh/re-render component without using window.location.reload()


I want to reload/refresh/re-render my component but without using ‍‍‍window.location.reload(). Is there any possible way to do so. I have tried with this.forceUpdate() and this.setState({ state: this.state }); but these are not actually helping me in my case.

 testDoneHandler(e) {
    if( this.state && e.origin === document.location.origin ) {
      if( e.data === 'testingClosed' ) {
        this.setState({ state: this.state });
      
      }
    }
  }



 componentDidMount() {
    window.addEventListener('message', this.testingClosed.bind(this));
  }

Any suggestion/help would be helpful.Thanks in advance


Solution

  • I think you need something like this:

    class t extends React.Component {
      state = {
        forceRerender: 0,
      };
      testDoneHandler(e) {
        if (this.state && e.origin === document.location.origin) {
          if (e.data === "testingClosed") {
            this.setState((value) => ({ forceRerender: value.forceRerender + 1 }));
          }
        }
      }
    
      componentDidMount() {
        window.addEventListener("message", this.testingClosed.bind(this));
      }
    
      console.log('forceUpdate', this.state.forceRerender);
    }