0

So as the title says, I'm playing around with websockets. So far all good, except for the fact that I can't make the page wait until we get a reponse. Now, I do actually have a good reason to do this; the requests times are about 2-10 ms due it going to 127.0.0.1 , so barely noticable. It is however long enough for the page to progress long enough to get to a part where the response is needed.
As you can tell, that is kind of a problem.
I am using the normal JS socket interface on the client and a golang websocket library on the backend.
Any ideas?

2 Answers 2

0

Just embed your part where a responds is needed inside

socket.onmessage = function (msg) {
    // part where msg.data is needed
}
Sign up to request clarification or add additional context in comments.

Comments

0

Are you using some Web libraries like ReactJs/VueuJs?

If you are using some library that you can manage the Browser DOM, you can use a Spinner strategy. Wen, you page first rendering you send to the user at the first time a Spinner and before your data cames you remove the spinner and show your page. If you prefer you can use a Skeleton in place of the spinner.

If you are using react you can do something like this.

import { useState } from 'react'

const Page = () => {
 const [loading, setLoading] = useState(true)
 cosnt [data, setData] = useState({})

 useEffect(() => {
   socket.on('message', (data) => {
     setData(data)
     setLoading(false)
   })
 }, [])

 return (<>
    { loading ? <Spinner /> : <Screen data={data} /> }
 </>)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.