S
S
semki0962020-02-15 13:17:37
React
semki096, 2020-02-15 13:17:37

How to organize the transfer of data to React received via websocket?

There is a service with socket API. You can connect to it from the server (not from the client). That is, as I understand it, I need to get this data on the server. I use this library https://github.com/websockets/ws and raise the client on the server, get the data:

const WebSocket = require('ws');
    const  ws  =  new  WebSocket ( ' wss://stream.... ' , {
    perMessageDeflate :  false 
    });
    ws.on('message', function incoming(data) {
        console.log(data);
    });


Question. How can I pass this data to my React component now? As far as I understand, I need to create a server, there is an example in the docs:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

And already in the component to accept data as if it were regular js? Is this the correct approach for Reacta, or maybe there are some subtleties?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2020-02-15
@semki096

Anything can be done on the server side. You can do everything yourself, you can use something like https://socket.io/
On the client, you need to subscribe to socket updates, for example, through useEffect by linking with the data in useState .
You can also wrap the connection in a React Context provider .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question