DEV Community

Huzaifa Rasheed
Huzaifa Rasheed

Posted on

3 2

How do abstract Socket.IO connections in your SPA.

When working with socketIO client in your SPA, it may become very hard to manage the socket instance, events emitters, and work with the callbacks in different places of the app. Especially when there are multiple different servers to connect with. What can be done?

Solution

We can create a closure that takes event callbacks as functions and return event emitters, to abstract socketIO implementation in a single file (let's call it SocketManager.js).

Example

import io from "socket.io-client";

const SocketManager = ({
  onCallback = () => {},
}) => {
  const socket = io(/* server url to connect */);

  // Callbacks
  socket.on('callback-event-name', (payload) => {
    onCallback && onCallback(payload);
  });

  // Emitters
  const emitEvent = (eventPayload) => {
    socket.emit('emit-event-name', eventPayload);
  };

  return {
    socket,
    emitEvent
  };
};

export default SocketManager;

Enter fullscreen mode Exit fullscreen mode

then we can use this in our React code like this

import React from "react";
import SocketManager from "./SocketManager.js";

const SocketConsumer = () => {
  const { emitEvent } = SocketManager({
    onCallback: handleCallback,
  });

  const handleCallback = (payload) => {
    /** Do something with the payload */
  };

  return <button onClick={emitEvent}>Fire Event</button>;
};

export default SocketConsumer;
Enter fullscreen mode Exit fullscreen mode

Hope this helps you in your projects. Thanks 🙂

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay