Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS + Socket.IO - Best way to handle socket connection

I'm trying to make a ReactJS realtime application with Node and Socket.IO, but I'm having a hard time figuring out the best way to handle my socket connection on the clientside.

I have multiple React components that all need some information from the server, and preferrably in realtime via the socket connection. But when importing the socket.io-client dependency and making the connection to the server in different files, I get multiple connections to the server, which doesn't really seem that optimal.

So I'm wondering if there's a better solution to share the connection between multiple components without having to create a new connection for each component. Maybe by making connection in the main app.js file and then passing it onto the child components for later use.

Some places online suggests using the context property to pass the socket variable, but React's own documentation highly discourage the use of context.

The following code is just an example, not the actual code since there's much more unnecessary code in the real project than needed to illustrate the problem.

foo.js

import React from 'react';
import io from 'socket.io-client';

const socket = io("http://localhost:3000");

class Foo extends React.Component {
    // ...
    componentDidMount() {
        socket.on("GetFooData", (data) => {
            this.setState({
                fooData: data
            });
        });
    }
    // ...
}

bar.js

import React from 'react';
import io from 'socket.io-client';

const socket = io("http://localhost:3000");

class Bar extends React.Component {
    // ...
    componentDidMount() {
        socket.on("GetBarData", (data) => {
            this.setState({
                barData: data
            });
        });
    }
    // ...
}

app.js

import React from 'react';
import ReactDOM from 'react-dom';
import Foo from './foo';
import Bar from './bar';

const App = () => {
    return (
        <div className="container">
            <Foo />
            <Bar />
        </div>
    );
};

ReactDOM.render(
    <App />,
    document.getElementById("root")
);
like image 932
Phoenix1355 Avatar asked Feb 14 '18 19:02

Phoenix1355


People also ask

How do I make my Socket.IO secure?

Setting the socket to be secured is done by: setting the secure flag - as you wrote ({secure: true}) OR by using https protocol when creating the server (instead of http) - which will set the secure flag to be true automatically.

How do I join a Socket.IO server in react?

Open the index. js file on the server, update the Socket.io code block to listen to the message event from the React app client, and log the message to the server's terminal. 1socketIO. on('connection', (socket) => { 2 console.

Should I use Socket.IO or WebSockets?

As said before, Socket.IO can fall back to technologies other than WebSockets when the client doesn't support it. If (for some reason) a WebSocket connection drops, it will not automatically reconnect… but guess what? Socket.IO handles that for you! Socket.IO APIs are built to be easier to work with.


1 Answers

You can create one socket connection and then export it ,like this,

import io from "socket.io-client";
let socket = io("http://localhost:8000/chat");
export default socket;

and then import it anywhere

import socket from "../../socket/socket";
like image 199
Ashad Nasim Avatar answered Oct 21 '22 15:10

Ashad Nasim