Socket API || React Native and Node JS || Step by Step Guide

Redmen Ishab
3 min readMay 22, 2021

As I was working in my project I had to create a socket api that broadcast an event every time a new notification is posted on the mongoose database. The notification listener resides on the react-native application.
The steps I used are as below to
I. Create a socket API in Node JS and connect and
II. Listen for event in React Native application.

Creating a Socket API in Node JS

We will be using socket.io to create webSocket because of it multiple advantages and simplicity in usage. The advantage points of socket.io are:

Step 1:
Install socket io.

yarn add socket.io

step 2: Init the socket

const httpServer = require("http").Server();
const io = require("socket.io")(httpServer)
// Socket connection , disconnection, emit will go here::

httpServer.listen(3000,()=> {
console.log("server initiated in port 3000")
});

step 3: Socket connection and disconnection

const httpServer = require("http").Server();
const io = require("socket.io")(httpServer)
io.on("connection", (socket) => {
console.log(`connect: ${socket.id}`);
//broadcasting event will go here::: socket.on("disconnect", () => {
console.log(`disconnect: ${socket.id}`);
});
});
httpServer.listen(3000,()=> {
console.log("server initiated in port 3000")
});

step 4: Broadcast the event from (NotificationController.js)

const NotificationController= {
...
postNotification:(req,res,next)=>{
try{
...Post notification goes here and
io.on("connection", (socket) => {
\\"notification" below is the name of event which should match to our event listener in client side. socket.emit("notification", { description: notification });
logger("notification emitted ::::", socket);
});
}
catch(err) console.log('error on posting notification",err);
}
}

Thats it. We deploy our changes to our server.

React Native /Client side connection to Socket API

We will use socket.io-client library for connection.

step 1: Install the library

yarn add socket.io-client

step 2: Connect : We assign the IP of our server or local IP ( Localhost doesn’t work between react-native and node js ) which then listens for events. Socket.on(“connect”,()=>{}) is executed on establishing connection with webSocket.

disconnect: socket.on(“disconnect”, () =>{}) is triggered on disconnection of webSocket.

event listener : socket.on(“EVENT_NAME”, (content)=>{}) method will execute when an event is sent in the websocket by server.

import io from "socket.io-client";
const socket = io("https://122.138.10.10");
\\Your server IP or local IP goes here
const NotificationScreen=(props:any)=>{
...
};
const [connected, setConnected] = React.useState(socket.connected);
const [currentTransport, setCurrentTransport] = React.useState(
socket.connected ? socket.io.engine.transport.name : "-",
);
React.useEffect(() => {
socket.on("connect", () => onConnectionStateUpdate());
\\establish connection
socket.on("disconnect", () => onConnectionStateUpdate());
\\listen for disconnection
socket.on("notification", (content) => onNotification(content));
\*event listener **"notification" is event name that should match with our eventName on the server */
return () => {
socket.off("connect"); \\on unmount the socket connections are off
socket.off("disconnect");
socket.off("notification");
};
}, []);
const onConnectionStateUpdate = () => {
console.log("socket connection status", socket.connected, socket);
setConnected(socket.connected);
if (socket.connected) {
socket.io.engine.on("upgrade", () => onUpgrade());
} else {
socket.io.engine.off("upgrade");
}
};
const onNotification = (content: any) => {
console.log("New notification triggered", { content });
};
const onUpgrade = () => {
setCurrentTransport(socket.io.engine.transport.name);
};
...
}

Thats it. The react-native client side will now establish connection and listen for the event until the component is unmounted.

I hope it helps ! Thanks and Best of luck !

--

--

Redmen Ishab

Software Engineer. Failed startup “Software Factory”. Working experience as CTO, SSE, Full Stack Dev, Mobile App Engineer, and Lecturer.