Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Huzaifa Rasheed
Huzaifa Rasheed

Posted on

     

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 itSocketManager.js).

Example

importiofrom"socket.io-client";constSocketManager=({onCallback=()=>{},})=>{constsocket=io(/* server url to connect */);// Callbackssocket.on('callback-event-name',(payload)=>{onCallback&&onCallback(payload);});// EmittersconstemitEvent=(eventPayload)=>{socket.emit('emit-event-name',eventPayload);};return{socket,emitEvent};};exportdefaultSocketManager;
Enter fullscreen modeExit fullscreen mode

then we can use this in our React code like this

importReactfrom"react";importSocketManagerfrom"./SocketManager.js";constSocketConsumer=()=>{const{emitEvent}=SocketManager({onCallback:handleCallback,});consthandleCallback=(payload)=>{/** Do something with the payload */};return<buttononClick={emitEvent}>FireEvent</button>;};exportdefaultSocketConsumer;
Enter fullscreen modeExit fullscreen mode

Hope this helps you in your projects. Thanks 🙂

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A software enthusiast ✨, currently living in the javascript universe. 🌌
  • Location
    Islamabad, Pakistan
  • Work
    Software Engineer
  • Joined

More fromHuzaifa Rasheed

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp