FabricioG
FabricioG

Reputation: 3310

Connecting socket io with react, not able to get data

I'm attempting to connect a component from React to get some data from the server with live updates via socket.io

In my express server I have the following: (partial but the relevant part)

const apiPort = 3000
const server = app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`))

io.on('connection', (client) => {
  client.on('subscribeToTimer', (interval) => {
    console.log('client is subscribing to timer with interval', interval);
    setInterval(() => {
      client.emit('timer', new Date());
    }, interval);
  });
});

io.listen(server);
console.log('listening on port ', apiPort);

I then have a helper api.js file on the client side:

import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:3000');

function subscribeToTimer(cb) {
  socket.on('timer', timestamp => cb(null, timestamp));
  socket.emit('subscribeToTimer', 1000);
}

export { subscribeToTimer }

I then import this method into my react component:

import { subscribeToTimer } from './api';

I then create a state and attempt to update it:

const [timestamp, setTimeStamp] = useState('no timestamp yet')

  useEffect(() => {
    subscribeToTimer((err, tstamp) => setTimeStamp);
    console.log(timestamp);
  });

On the server side I get the console log:

client is subscribing to timer with interval 1000

On the client side it console.logs:

'no timestamp yet'

I'm not getting the update from the socket. Any idea what I'm doing wrong? I'm following a tutorial and incorporating it into my react project.

Upvotes: 1

Views: 705

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

Pass the tstamp to the setTimeStamp function, you are just passing the reference of the function.

Try this.

const [timestamp, setTimeStamp] = useState('no timestamp yet')
  useEffect(() => {
    subscribeToTimer((err, tstamp) => setTimeStamp(tstamp));
    console.log(timestamp);
  });

Upvotes: 2

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

I believe your problem is here:

useEffect(() => {
    subscribeToTimer((err, tstamp) => setTimeStamp(tstamp));
    console.log(timestamp);
  }

You are not assign8ng anything to your state

Upvotes: 1

Related Questions