Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an application in the kill app on react native?

I want to change the state data from the API when the application is killed by the user.

I have tried using the componentWillUnmount to change data when the application closes, I also use the AppState

  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!')
    }
    this.setState({ appState: nextAppState })
  }


I want that when the application is killed by the user, it can change the state automatically.

like image 353
zidniryi Avatar asked Dec 11 '22 01:12

zidniryi


1 Answers

nextAppState === 'inactive' or checking if background does not tell you if the app is "Killed" (swiped out) or not.

Because when the native layer is killed then the javascript engine is killed as well. So there is no way to tell javascript that the app is killed.

If you just want to initialize something after the app is killed, you can fire some function inside constructor or componentDidMount of a base component which you know that it will be mounted only once for your app.

added: Now we may (maybe prefer to) use useEffect(()=>{}, []) instead of examples above.

If you really want to make sure the app is killed before, maybe you can store nextAppState into some persisted store and check if the value matched one of inactive or background since the app state will not be changed on the initial startup of the app.

like image 195
foloinfo Avatar answered Dec 28 '22 06:12

foloinfo