Last active
September 22, 2023 19:28
-
-
Save jacwright/31c911f8876fab34f8c49e0ebf79885d to your computer and use it in GitHub Desktop.
Svelte Convex query store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { ConvexClient } from 'convex/browser'; | |
import type { FunctionReference } from 'convex/server'; | |
import { derived, writable } from 'svelte/store'; | |
export function queryResults<Query extends FunctionReference<'query'>>( | |
client: ConvexClient, | |
query: Query, | |
initialArgs: Query['_args'] | |
): Query['_returnType'] { | |
const args = writable(initialArgs); | |
const loading = writable(false); | |
const error = writable<Error>(null); | |
const { subscribe } = derived(args, (args, set) => { | |
loading.set(true); | |
const callback = (result: Query['_returnType']) => { | |
set(result); | |
loading.set(result === undefined); | |
error.set(null); | |
}; | |
return client.onUpdate(query, args, callback, error.set).unsubscribe; | |
}); | |
return { | |
subscribe, | |
args, | |
loading, | |
error, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use like this: