Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs call specific function when page refreshed or closed

I have a component like:

import React, { PropTypes, Component } from 'react'


class MyView extends Component {

    componentDidMount() {
        window.addEventListener('onbeforeunload', this.saveState())
    }

    componentWillUnmount() {
        window.removeEventListener('beforeunload', this.saveState())
    }

    saveState() {
        alert("exiting")
    }

    render() {

        return (
            <div>
                Something
            </div>
        )
    }

}

export default MyView

Here when a user refresh the page I want to call a specific funtion and when call is finished I want the page to be refreshed. Same when user closes the page.

In my above code I am adding an event listener onbeforeunload and calling a saveState function.

But here my componentDidMount is working normally. onbeforeunload and saveState function is called normally when page is loaded not when page is refreshed or exited.

What is wrong in here and how can I call specific funcitn or give alert when someone exits or refresh the page in react ?

In the above code

like image 787
varad Avatar asked Nov 09 '22 10:11

varad


1 Answers

Attach beforeunload event on top level component and on beforeunload event make render empty which will trigger componentWillUnmount of all child components.

import React, { PropTypes, Component } from 'react'

class App extends Component {
    componentDidMount() {
      window.addEventListener('beforeunload', () =>{
          this.setState({appended:true});
      });
    }
    render() {
      if(this.state.appended){
        return false;
      }else{
        return (<MyView />)
      }
    }
}


class MyView extends Component {


  componentWillUnmount() {
    this.saveState()
  }

  saveState() {
    alert("exiting")
  }

  render() {

    return (
        <div>
            Something
        </div>
    )
  }

}

export default MyView

Hope this work for you.

like image 101
vijay Avatar answered Nov 15 '22 14:11

vijay