Client Side (Socket) - React & React Native

First of all you'll need to install socket.io-client

yarn add socket.io-client

Socket Manager

Create a file named Socket

import io, { Socket } from 'socket.io-client';

import { getItemAsync } from "expo-secure-store"; //Or ReactJs with localStorage

import { host } from "./API";

let socket: Socket;

export const getSocket = (): Socket => {

    if (!socket && host) {

        socket = io(host, {
            transports: ['websocket'],
            forceNew: true,
            upgrade: false,
        });

        socket.on("connect", () => {
            getItemAsync("token").then((token) => {
                if (token) {
                    socketAuth(token);
                }
            });
        })

        socket.on("reconnect", () => {
            getItemAsync("token").then((token) => {
                if (token) {
                    socketAuth(token);
                }
            })
        })

    }
 
    return socket;
};

export const socketAuth = (token: string) => {
    socket.emit("auth", token)
}

This code file establishes a WebSocket client in a TypeScript environment using the 'socket.io-client' library. Its primary purpose is to provide a reusable socket connection that can be authenticated with an access token when connecting or reconnecting to the server. This module simplifies the process of managing WebSocket connections and authentication for applications that require real-time communication.

useSocket Hook

This code defines a custom React Hook named useSocket that facilitates real-time WebSocket communication in React applications. It imports the necessary functions from the socket.io-client library and establishes a WebSocket connection through getSocket(). The Hook takes a callback function onReactive as an argument, which is triggered when certain events, denoted as "reactive," occur on the WebSocket. It manages event listeners for the "reactive" event and provides the WebSocket instance and an authentication function. This Hook abstracts WebSocket setup and event handling, making it easier to integrate real-time features into React components.

Real usage

During user Connection or during the app load, you can just query the socket server for register our user into our service. Example in HomeScreen of one of our App.

Last updated

Was this helpful?