Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native : change state when app is in background

Tags:

react-native

I create a simple app that using React Native AppState:

import React, {Component} from 'react'
import {AppState, Text , View} from 'react-native'


export default  class AppStateExample extends  React.Component {

  constructor(props){
    super(props);
    this.state = {
      name:'not change'
    }
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {

    if(AppState.currentState=='background'){
      console.log('background mode');
      this.setState({name:'back'});
    }
    if(AppState.currentState =='active'){
      //...
    }
  };


  render() {
    return (
      <View>
        <Text>State Name : {this.state.name}</Text>
      </View>
    );
  }

}

And when I try switch app from foreground to background and then background to foreground console.log('background mode'); work very well and console print 'background mode'

BUT

The this.setState({name:'back'}); not working and I see 'not change' text in view

like image 929
Reza Mazarlou Avatar asked Nov 08 '22 06:11

Reza Mazarlou


1 Answers

Actually, based on React Native Docs on AppState change for Functional Component I prefer to write code like below:

import { useRef, useState, useEffect } from "react";
import { AppState } from "react-native";

const AppStateManager = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    AppState.addEventListener("change", handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", handleAppStateChange);
    };
  }, []);

  const handleAppStateChange = (nextAppState) => {
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      console.log("App has come to the foreground!");
    }

    appState.current = nextAppState;
    setAppStateVisible(appState.current);
    console.log("AppState", appState.current);
  };

  return null;
};

export default AppStateManager;

Surely, we can use this component in the root of the project just like a React Component:

~~~
  <App>
    ~~
    <AppStateManager />
    ~~
.
.
.
like image 159
AmerllicA Avatar answered Nov 15 '22 13:11

AmerllicA