hey ! I want to create an app that makes API calls to fetch financial data (live stock price for example), this price will be displayed on the UI and needs to have the lowest latency possible, this is done with a websocket connection, the app runs on localhost, so i want to avoid fetching this live price with a backend as intermediary, reason being i want very low latency on that data (the live stock price). how would this work in Qwik ? (meaning, how can I display price directly on the frontend ?) thanks in advance
#best approach for fetching and display live price
9 messages · Page 1 of 1 (latest)
So you've got a websocket endpoint and you want to display the result in realtime on the client ?
const socket = new WebSocket("wss://endpoint");
const useRealTimePrice = $(() => {
const price = useSignal<number>();
useTask$(() => {
const cb = (event) => (price.value = event.data);
socket.addEventListener("message", cb );
return () => socket.removeEventListener("message", cb );
})
})
export default component$(() => {
const price = useRealTimePrice();
return <p>{price.value}</p>
})
Here I use the browser compatible Websocket object. It might not work on all server runtime. But the idea is the same.
so this is SSG right ? not SSR ?
forgive me if i said something dumb ..
No worry, you're right we need to split it in 2 in case we are doing SSR.
const socket = new WebSocket("wss://endpoint");
const useRealTimePrice = $(() => {
const price = useSignal<number>();
useTask$(() => {
if (isBrowser) return; // Default to useVisibleTask$
const cb = (event) => (price.value = event.data);
socket.addEventListener("message", cb, { once: true });
});
useVisibleTask$(() => {
const cb = (event) => (price.value = event.data);
socket.addEventListener("message", cb );
return () => socket.removeEventListener("message", cb );
});
})
export default component$(() => {
const price = useRealTimePrice();
return <p>{price.value}</p>
})
When you run the code on the server useTask$ will run once (you don't need to listen on changes)
When the client runs the code useVisibleTask$ will run and you start listening on the changes
If you arrive on this component from a SPA navigation, useTask$ will run on the client so we skip in favor of useVisibleTask$
i see, so this is kinda like a combination of SSR and SSG, so at the start we load price both on server and client, once price is loaded in the client, that's it the client will continuously listen for real-time price updates
yes