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?
Just embed your part where a responds is needed inside
socket.onmessage = function (msg) {
// part where msg.data is needed
}
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} /> }
</>)
}