Rama Krishna
Rama Krishna

Reputation: 13

React native appstate using to check user online and offline

I am newbie to React Native, I am developing messaging app on react native. How can I implement functionality to change user online/offline status if the appState is Active/inActive and exactly in which page (at the root/index) or after login at HomePage, will it be global? used across all the pages in application?

Thanks in advance.

Upvotes: 1

Views: 3355

Answers (1)

Arbnor
Arbnor

Reputation: 2352

React Native itself offers AppState and you can easily check there in your App.js if the app is currently in the background or just active. If the app is active, then you can call your backend function to set the online state to true. Since you are doing this in your root file (App.js), the listener works across all files.

import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";

const AppStateExample = () => {
  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"
    ) {
      // TODO SET USERS ONLINE STATUS TO TRUE
    } else {
     // TODO SET USERS ONLINE STATUS TO FALSE
    }

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

  return (
    <View style={styles.container}>
      <Text>Current state is: {appStateVisible}</Text>
    </View>
  );
};

Upvotes: 2

Related Questions