DEV Community

loading...
Cover image for Custom hook to store user online presence using firebase in React Native

Custom hook to store user online presence using firebase in React Native

Arun D Nambissan
https://ArunD.in | #developer 👨‍💻
・2 min read

Here I will show how to create a custom react hook which can be used in your react native application to store the logged in user's online presence.

I am using the following packages in my project to implement our requirement:

I believe that you have already set up above packages in your project, if not you can refer the above links.

Identifying if the user is online

Firstly, we can create a new file for our hook. I am naming it as useOnlinePresence.js and adding the first few lines of code. Also we can import the required packages to the file.

import NetInfo from "@react-native-community/netinfo";
import database from '@react-native-firebase/database';
import auth from '@react-native-firebase/auth';

export default useOnlinePresence = () => {

}

Enter fullscreen mode Exit fullscreen mode

Now we can add react's useEffect hook and we can add an event listener inside it, which watches the network state using the package NetInfo.

export default useOnlinePresence = () => {
    useEffect(() => {
        const unsubscribe = NetInfo.addEventListener(state => {
            if (state.isConnected) {
                console.log("user online")
            }
        });

        return unsubscribe;
    }, []);
}

Enter fullscreen mode Exit fullscreen mode

So now we can identify when the user gets online and we can save it to firebase realtime database.

Saving online presence to database

We can create a new function saveOnlineStatus, here we can get the authenticated user's uid by calling the firebase auth method auth().currentUser.uid. Then create a new realtime db reference using the uid and set the value as true.

export default useOnlinePresence = () => {
    const saveOnlineStatus = () => {
        const userId = auth().currentUser.uid;

        const reference = database().ref(`/online/${userId}`);

        reference.set(true)
        .then(() => {
             console.log('Online status set as true')
        });
    }

    useEffect(() => {
        const unsubscribe = NetInfo.addEventListener(state => {
            if (state.isConnected) {
                saveOnlineStatus();
            }
        });

        return unsubscribe;
    }, []);
}

Enter fullscreen mode Exit fullscreen mode

Deleting online presence from DB

Now we need to delete the saved data once the user goes offline, you can use the below lines of code to achieve that.

reference
.onDisconnect()
.remove()
.then(() => console.log('On disconnect configured'));
Enter fullscreen mode Exit fullscreen mode

The firebase server runs the remove method once the user goes offline or the user suddenly quits the application.

Conclusion

So we are done with the custom hook implementation and the useOnlinePresence.js file is given below. You can call the hook useOnlinePresence from the layout component which gets rendered after successful login.

import { useEffect } from "react";
import NetInfo from "@react-native-community/netinfo";
import database from '@react-native-firebase/database';
import auth from '@react-native-firebase/auth'; 

export default useOnlinePresence = () => {
    const saveOnlineStatus = () => {
        const userId = auth().currentUser.uid;

        const reference = database().ref(`/online/${userId}`);

        reference.set(true)
        .then(() => {
             console.log('Online status set as true')
        });

        reference
        .onDisconnect()
        .remove()
        .then(() => console.log('On disconnect configured'));
    }

    useEffect(() => {
        const unsubscribe = NetInfo.addEventListener(state => {
            if (state.isConnected) {
                saveOnlineStatus();
            }
        });

        return unsubscribe;
    }, []);
}

Enter fullscreen mode Exit fullscreen mode

You can see the data saved in realtime database of your firebase project - https://console.firebase.google.com/project/<your-project-id>/database

Alt Text


Cover Photo by ROBIN WORRALL on Unsplash

Discussion (0)