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

191
Visualizações
nested websocket function always returning undefined

I'm using websockets from this library: https://www.npmjs.com/package/websocket
This is a function in React.ts 17 that successfully retrieves the data from the server, but fails to return the values of the function itself.

    const recieveMessages = () => {

        client.onmessage = (message: any) => {
            const dataFromServer = JSON.parse(message.data)
            console.log(dataFromServer) //This successfully logs the data
            return dataFromServer //This is always returned as undefined
        }
          //I've tried a few versions with the return statement here without any success.
    }

How can I make the recieveMessages function return the data from the client.onmessage function?

Update: I'm trying to seperate all the logic into a seperate React hook(useWebSocket) which currently looks like this:

import { w3cwebsocket } from 'websocket'

export const useWebSocket = () => {
    const client = new w3cwebsocket('ws://127.0.0.1:8000')

    const connectToServer = () => {
        client.onopen = () => { console.log('Websocket client connected') }
    }

    const recieveMessages = () => {
        client.onmessage = (message: any) => {
            const dataFromServer = JSON.parse(message.data)
            console.log('reply from server: ', dataFromServer)
            return dataFromServer
        }
    }

    const sendMessage = (message: any) => {
        client.send(JSON.stringify('lol'))
    }
    const onCloseServer = (event: CloseEvent) => {
        console.log(event)
    }

    return {
        connectToServer,
        recieveMessages,
        sendMessage,
        onCloseServer
    }
}

I'm then trying to run the function inside the useEffect in a separate component like this: The desire is to set the following data inside the local state of this component.

    useEffect(() => {
        recieveMessages()
        setState(recieveMessages()) //This is always undefined
    }, [])
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This calls for a useState hook inside your useWebSocket hook.
Whenever client.onmessage receives a message, store that message inside of a state and update it every time another message is received.

Then return the state from the hook.

import { useState } from 'react'
import { w3cwebsocket } from 'websocket'

export const useWebSocket = () => {
  const [receivedMessage, setReceivedMessage] = useState('')
  const client = new w3cwebsocket('ws://127.0.0.1:8000')

  client.onmessage = (message: any) => {
    const dataFromServer = JSON.parse(message.data)
    setReceivedMessage(dataFromServer)
  }

  const sendMessage = (message: any) => {
    client.send(JSON.stringify(message))
  }

  return {
    receivedMessage,
    sendMessage,
  }
}

Then implement it like so. The receivedMessage value is the state that will be updated and can be monitered with a useEffect hook to do something whenever a message has been received.

const { receivedMessage, sendMessage } = useWebSocket()

useEffect(() => {
  if (receivedMessage !== '') {
    // Do something whenever the received message is changed.
    sendMessage('Received you loud and clear')
  }
}, [receivedMessage])
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