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

138
Visualizações
Socket.io resets my pre-defined state variables when listening to a message

I have seen similar questions, but none have fixed my problem unfortunately.

I have a component which saves some states on mount, using useEffect:

useEffect(() => {
    const openWebPianoUtil = new OpenWebPiano();
    openWebPianoUtil.init(new AudioContext())
    setOpenWebPianoInstance(openWebPianoUtil);

    return () => socket.disconnect();
}, []);

Considering that setOpenWebPianoInstance is a state setter function.

I have another useEffect hook in that component that will trigger by the openWebPianoInstance state, and will listen to the socket messages:

 useEffect(() => {
    console.log(openWebPianoInstance);
    socket.on("noteOn", (note) => {
        console.log(openWebPianoInstance);
        console.log('got a note from socket: ', note);
        onNoteChange(note, true);
    });
}, [openWebPianoInstance])

While the first console.log(openWebPianoInstance) in the useEffect will show the updated data of openWebPianoInstance, in the socket.on callback, the openWebPianoInstance state is suddenly null again (which is its initial state).

I tried putting the socket code in the first useEffect hook which listens to the component mount, but it also did the same thing.

Why is the state reset every time the socket message is received? Does it do something behind the scenes that i'm missing?

about 4 years ago · Juan Pablo Isaza
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