Home > Back-end >  How to get current state value inside websocket onmessage?
How to get current state value inside websocket onmessage?

Time:12-06

I'm building a website with react(Next.js) and websocket like below.

const [selectedId, setSelectedId] = useState(null)
const ws = useRef()

useEffect(() => {
  ws.current = new WebSocket(...)

  ws.current.onopen = () => {...}

  ws.current.onmessage = event => {
      console.log(selectedId)
  }

  ...

}, [selectedId])

Inside onmessage, console always returns same value even user set other value with setSelectedId. I know that when websocket initialized, it will return initial value. But I need to get current state inside onmessage. Is there a solution on this? Or is it the only way to reconnect websocket to get changed state?

CodePudding user response:

Your useEffect runs after the component has first mounted and keeps the initial value of selectedId in a closure which it returns on every message. To update this based on the value of selectedId you can add another effect like

useEffect(() => {
    if(ws.current)
        ws.current.onmessage = () => console.log(selectedId)
}, [selectedId])

which replaces the old event handler with one that uses the updated value of selectedId.

  • Related