Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

84
Vistas
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
    }, [])
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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])
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.