Skip to content

Instantly share code, notes, and snippets.

@outerlook
Last active June 9, 2021 17:37
Show Gist options
  • Save outerlook/09741edf2a109727395bf785e716e2fb to your computer and use it in GitHub Desktop.
Save outerlook/09741edf2a109727395bf785e716e2fb to your computer and use it in GitHub Desktop.
GQLess svelte binding
import { writable } from 'svelte/store'
import type { ResolveOptions } from 'gqless/src/Client/resolvers'
import { client, resolved } from '$gqless/index'
import type { Selection } from 'gqless'
import { onDestroy } from 'svelte'
export const queryStore = <T = unknown>(
dataFn: () => T,
opts?: ResolveOptions<T>
) => {
const hookSelections = new Set<Selection>()
const promise = resolved(dataFn, {
...opts,
onSelection: s => {
opts?.onSelection?.(s)
hookSelections.add(s)
}
})
const res = writable(promise)
const { eventHandler } = client
const unsubscribeFetch = eventHandler.onCacheChangeSubscribe(
({ selection, data }) => {
if (hookSelections.has(selection)) {
res.set(resolved(dataFn))
}
}
)
onDestroy(() => {
unsubscribeFetch()
})
return res
}
<script lang="ts">
import {queryStore} from "gqless-svelte/autoQuery";
import {query} from "$gqless";
const promise = queryStore(() => query.me.name)
</script>
{#await $promise then name}
{ name }
{/await}
<!-- It should update on mutations -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment