How To Detect Onresume And Onpause On React Native Es6
How can I detect any method from background to foreground es6? Is this possible in React-native? and is there any class or tool that could help with this type of method?
Solution 1:
Try this, it working for me
importReact, {Component} from'react'import {AppState, Text} from'react-native'classAppStateExampleextendsComponent {
  state = {
    appState: AppState.currentState
  }
  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }
  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }
  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }
  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }
}
Solution 2:
As an update to the existing answer, removeEventListener(type, handler) has been deprecated (since September 2021):
Use the remove() method on the event subscription returned by addEventListener()
Using class component
importReact, {Component} from'react'import {AppState, Text} from'react-native'classAppStateExampleextendsComponent {
  state = {
    appState: AppState.currentState
  }
  eventListenerSubscription = null;
  componentDidMount() {
    this.eventListenerSubscription = AppState.addEventListener('change', this._handleAppStateChange);
  }
  componentWillUnmount() {
    this.eventListenerSubscription.remove();
  }
  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }
  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }
}
Using hooks
importReact, { useState, useEffect } from'react';
import { AppState, Text } from'react-native';
functionAppStateExample() {
  const [appState, setAppState] = useState(AppState.currentState);
  var eventListenerSubscription;
  const_handleAppStateChange = nextAppState => {
    if (appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!');
    }
    setAppState(nextAppState);
  };
  useEffect(() => {
    //on mount
    eventListenerSubscription = AppState.addEventListener('change', _handleAppStateChange);
    return() => {
      // on unmount
      eventListenerSubscription.remove();
    };
  }, []);
  return<Text>Current state is: {appState}</Text>;
}
exportdefaultAppStateExample;
Post a Comment for "How To Detect Onresume And Onpause On React Native Es6"