How to implement external subscription management? Websocket, timeouts, interval, etc, missing onMount #635
-
Hello! In libraries like nanostores or Svelte, there is an onMount method that makes it easy to manage subscriptions, such as for WebSocket updates or intervals. For example: const $steps = atom(0);
onMount($steps, () => {
// This will be called after $steps got any subscription
const interval = setInterval(() => $steps.set(s => s + 1), 1000);
return () => clearInterval(interval);
}); I’m trying to achieve something similar with preact-signals. I’ve seen discussions in the issues mentioning that signals have internal What is the recommended way to handle subscriptions like this in preact-signals? Is there a built-in pattern or best practice to achieve this? Thank you! EDIT 1: Signal.subtle.watched |
Beta Was this translation helpful? Give feedback.
Replies: 0 comments 6 replies
-
Making a subscription is basically a side-effect so using something The effect will run onMount and based on dependencies re-run again, in your case you don't want it to rerun so signals would be accessed with untracked or peek. only mountinguseSignalEffect(() => {
const unsubsribe = subscribeToSomeWebsocket() // will be called when the component mounts
return unsubscribe // will be called when the component unmounts
}) with updatesuseSignalEffect(() => {
const unsubsribe = subscribeToSomeWebsocket(id.value) // will be called when the component mounts and id signal updates
return unsubscribe // will be called when the component unmounts and id signal updates
}) |
Beta Was this translation helpful? Give feedback.
Making a subscription is basically a side-effect so using something
useSignalEffect
in signals oruseEffect(()=>,[])
in hooks would do that.The effect will run onMount and based on dependencies re-run again, in your case you don't want it to rerun so signals would be accessed with untracked or peek.
only mounting
with updates