Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!