Last active
June 9, 2021 17:37
-
-
Save outerlook/09741edf2a109727395bf785e716e2fb to your computer and use it in GitHub Desktop.
GQLess svelte binding
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 { 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 | |
} | |
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
<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