How can I generate stateful data within a function, and have components react to updates? #15465
Unanswered
MaddyGuthridge
asked this question in
Q&A
Replies: 1 comment 2 replies
-
// ContentUrl.svelte.ts
import { subscribeToContent } from "./contentObserver";
export class ContentUrl {
#liveUrl = $state('');
#cleanUp: Function | undefined;
constructor(url: string) {
this.#cleanUp = subscribeToContent(url, () => {
this.#liveUrl = `${url}#${new Date().getTime()}`;
});
}
dispose() {
this.#cleanUp?.();
this.#cleanUp = undefined;
}
get liveUrl() {
return this.#liveUrl;
}
} Then, in the script of a component: import { ContentUrl } from "./ContentUrl.svelte.js";
import { onMount } from "svelte";
const contentUrl = new ContentUrl(url);
onMount(() => () => contentUrl.dispose()); No |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello! I'm trying to implement a system where certain data (eg images) automatically reload when they are changed on the server. I've set up an observer system, where components can register a callback for when the content has changed, but am running into issues integrating it nicely into my svelte code.
Currently, I'm using a simple Svelte component which wraps around the subscribe function, and updates a bindable prop whenever data is changed. Essentially, given the URL of some content, it produces a new URL with a hash of the current timestamp, which causes the browser to reload the image, without disrupting server-side caching.
I can use the component like this:
However, given there is no actual UI content, the fact that I'm using a Svelte component feels less than ideal. As such, I'd really appreciate suggestions for how I can implement this in a re-usable way without making it a component. Ideally, this would be a function that I can call from a component, which returns a
$state
proxy which it will then update as-required. This function will need to unsubscribe from the observer when the component is dismounted, to avoid resource leaks.Beta Was this translation helpful? Give feedback.
All reactions