How use remote functions with singleton classes? #15740
-
|
Is it possible or recommended to use remote functions inside a singleton class? For example, I want a shared store that I can use in different components. But I cannot figure out how to achieve this with remote functions and have it be responsive to mutations. This doesn't even compile but this possibly captures what I am trying to achieve. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
As you noticed already, classes cannot contain async initializers, but there is a synchronous API on remote function queries that should (in theory) work for your use-case: class Printers {
printers = $derived(getAllPrinters())
checkOnline() {
if (!this.printers.ready) return // ensures .current is not undefined
for (const printer of this.printers.current) {
console.log(printer.status)
}
}
}There are synchronous values for:
But the next problem you're likely to run into is that remote queries are not allowed to be called outside of a reactive context anymore, so this probably still wouldn't work unless you instantiate the class in a component tree and pass it down to components via context, as singletons are not recommended with SSR. |
Beta Was this translation helpful? Give feedback.
As you noticed already, classes cannot contain async initializers, but there is a synchronous API on remote function queries that should (in theory) work for your use-case:
There are synchronous values for:
.current(which holds the current value of the query).ready(for initial load and with type narrowing to ensure.currentis not undefined).loading(also true if currently refreshing and.currentstill holding the stale previous value).errorto get th…