1771771771
Denoβ€’3y agoβ€’
10 replies
177177177

Signal value not updating from inside of `for await of` loop inside of an IIFE

// routes/connect.tsx
import type { FunctionComponent } from 'preact'
import type { PageProps } from '$fresh/server.ts'

const api_version = 10

export default ((props) => {
  const message = useSignal('Connecting')

  ;(async () => {
    const wss = new WebSocketStream(`${
        (await (
          await fetch(`https://discord.com/api/v${api_version}/gateway`)
        ).json()).url
      }/?v=${api_version}&encoding=json`)
    const { readable } = await wss.opened

    for await (const msg of readable) {
      message.value = msg // not updating message.value

      console.log(msg) // this works
    }
  })()

  message.value = 'updated outside of the IIFE' // this works too

  return (
    <div class='max-w-screen-md mx-auto flex flex-col items-center justify-center'>
      <div class='flex gap-8 py-6'>
        <button>{message}</button>
      </div>
    </div>
  )
}) satisfies <FunctionComponent<PageProps>>

I'm using an IIFE here because otherwise the
for await of
loop will block the code and page keeps loading till
WebSocketStream
connection ends, so I did that.
But why does setting
message.value = msg
not update the button text, it is stuck at the initial
Connecting
text.
But when I set
message.value = 'updated outside of the IIFE'
then it works fine, the value is updating as expected.
The
console.log(msg)
inside the IIFE's
for await of
loop also works and logs the
msg
to the console, but still
message.value = msg
doesn't. Why ??
Was this page helpful?