How to send data which arrived on post endpoint through io.emit? NodeJS + React

Viewed 33

I am new in the MERN world and I need your help. I am building a small dashboard app with charts in ReactJS. This app receiving data from the Node.js server every 5 seconds. I imagine my workflow like this:

  1. server is receiving data on a POST request from NodeRED,
  2. when the POST request is triggered I would like to take the request body and send it through io.emit to the Client component. This is what I have tried, but it is not working...
.
.
.
let variable1 = 0; <-initial value

io.on("connection", (socket) => {
  console.log("Client connected");
  io.emit("event1", {name: "Test", value: variable1});
    
  socket.on("disconnect", () => {
    console.log("Client disconnected!");
  });
});

const postMeasurement = async (req, res, next) => {
  const { value } = req.body;
  variable1=value;
.
.
.

Thank you in advance for your time and help.

2 Answers

You are not emitting the event.

io.emit("event1", {name: "Test", value:new_value});

now you will emit an event with the correct value. Now, you can choose how to implement regular calls . Easiest would be in setInterval ,

setInterval(async()=>{
 let res = await POST_API_CALL_TO_NODE_RED;
  io.emit("event1", {name: "Test", value:res.body.val});
},5000)

To start, create the event first with io.emit

io.on('connection',(socket)=>{
  console.log('Client Connected');
  io.emit('myevent','data_goes_here');
  socket.on('disconnect',()=>{console.log('Client Disconnected')});
});

Now on your regular JS file:

var dataGotten;
// recieve event
socket.on('myevent',(data)=>{
  dataGotten=data;
});

Now to send back to your nodejs file:

// data comes back in parameter
socket.on('myevent',(data)=>{
  dataGotten=data;
  socket.emit('gottenEvent',true);
});

To collect the data from the socket.io we also use the socket.on:

io.on('connection',(socket)=>{
  console.log('Client Connected');
  io.emit('myevent','data_goes_here');
  socket.on('disconnect',()=>{console.log('Client Disconnected')});
  socket.on('gottenEvent',(isTrue)=>{
    if(isTrue){
      console.log('Client Successfully Recieved Message!');
    }
  }
});
Related