Skip to content

Instantly share code, notes, and snippets.

@jacwright
Last active September 22, 2023 19:28
Show Gist options
  • Save jacwright/31c911f8876fab34f8c49e0ebf79885d to your computer and use it in GitHub Desktop.
Save jacwright/31c911f8876fab34f8c49e0ebf79885d to your computer and use it in GitHub Desktop.
Svelte Convex query store
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,
};
}
@jacwright
Copy link
Author

jacwright commented Sep 22, 2023

Use like this:

<script>
// ...
const sum = queryResults(client, api.myFunctions.sum, { a: 1, b: 2 });
const { args, loading, error } = query;

setTimeout(() => {
  args({ a: 10, b: 20 });
}, 1000);
</script>

<strong>Sum:</strong>
{#if $loading}
  ...
{:else if $error}
  {$error.message}
{:else}
  {$sum}
{/if}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment