Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Socket io delay one event

I have connected socket io to Webhook and it succeeds. It can get information and can express But I'm stuck with one problem. When the desired value is displayed on the client-side, the response is delayed. For example, when the server-side detects an event will show on console.log(); But it won't show on the client-side. But when the server-side detects the event again (second time) The value saved the first time is sent to the client-side, and if the server detects the event again (third time) The second event value is sent to the client-side, which means it will delay the event one time. How can I fix this incident?

// Server
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io', { 
    transports: ['websocket', 'polling'] 
})(http, {
    cors: {
        origin:'*'
    }
});
const bodyParser = require("body-parser");


PORT = 8080;

io.on('connection', socket => {
app.use(bodyParser.json());
app.post('/api', (req, res) => {
 
    let x = req.body[0];
    let dates = x.created_date; 
    let name = x.name; 
    let watchlist = x.watchlist[Object];

if (watchlist == "Matched"){
  console.log("Date :", dates)
  console.log("Name :", name)
  io.emit('FromAPI', dates, name);
}
else {
  console.log("Unmatch")
}
res.status(200).end("Successfully");
    
});
console.log('Socket connected');
socket.on('disconnect', () => { console.log('Socket disconnected')});
});

http.listen(PORT, () => {
console.log(`Server : http://localhost: ${PORT}`);
});

// Client
import { useEffect, useState } from 'react';
import io from 'socket.io-client';
const socket = io("http://localhost:8080", { transports: ['websocket', 'polling'] });


export default function App() {
   const [date, setDate] = useState('');
   const [name, setName] = useState('');
   const [hook_event, setHook_event] = useState([
     { "date": date, "name": name},
     { "date": date, "name": name}
   ]);
   
  
  useEffect(() => {
    socket.on('FromAPI', (date, name) => {
      setDate(date);
      setName(name);

      hook_event.unshift({"date": date, "name": name});
      hook_event.pop();
    })
  }, [];

  return (
    <>      
       <p>Date : {hook_event[0].date} and {hook_event[0].name}</p>
       <p>Date : {hook_event[1].date} and {hook_event[1].name}</p>
    </> 
  );
};

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think I found the problem.

    const [countState, setCountState] = useState() 

    useEffect(() => {
    socket.on('FromAPI', (date, name) => {
      setDate(date);
      setName(name);

      hook_event.unshift({"date": date, "name": name});
      hook_event.pop();
      setCountState(hook_event[0])
    })
    }, [setCountState]; // update setCountState
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda