Search code examples
javascriptreact-nativetimer

How do i make a timer?


I'd like to time how long a user has been on my app, so for example, when my react native iOS app moves in to the foreground. Then as soon as it moves to the background, i would like to capture the number of seconds it was in the foreground for (and then send it to analytics, but that's another task). Here's what i'm doing so far, but it its saying that it 'cannot read property 'second' of undefined'. How do i achieve this result?

class Home extends Component {

  constructor(props) {
      super(props)

      this.state = {

        second: 0
      }
  }

 componentDidMount = async () => {

    AppState.addEventListener('change', this.onAppStateChange) 
 }

  //Tracks when app is brought to foreground or background
  onAppStateChange(appState) {    
    if(appState === 'active') {   
      //User is ON App 
      console.log('ON');

      this.timer = setInterval(() => {
        this.setState ({ second: this.state.second + 1 }) },
        1000
      )

    }
    if(appState === 'background') {
      //User is OFF App
      console.log('OFF');
      clearInterval(this.timer);
      console.log(this.state.second)
    }

  }


}

Solution

  • Just Bind this to your function in the constructor or use arrow function like this:

    this.onAppStateChange = this.onAppStateChange.bind(this)
    or onAppStateChange = () => {
      //your code
    }