1

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.

2 Answers 2

2

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);
  });
Sign up to request clarification or add additional context in comments.

Comments

1

I believe your problem is here:

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

You are not assign8ng anything to your state

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.