varad
varad

Reputation: 8029

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

Upvotes: 5

Views: 13136

Answers (2)

vijay
vijay

Reputation: 631

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.

Upvotes: 1

user5738822
user5738822

Reputation:

According to this, try this syntax :

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

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

Upvotes: 0

Related Questions