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;
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;
Hope this helps you in your projects. Thanks 🙂
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse