vishalbalaji / trpc-svelte-query-adapter

A simple adapter to use `@tanstack/svelte-query` with trpc, similar to `@trpc/react-query`.
71 stars 7 forks source link

Add a `lazy` option to make `createQuery`, `createInfiniteQuery` and `createQueries`. #49

Closed vishalbalaji closed 2 months ago

vishalbalaji commented 2 months ago

This option would disable the query by default and return a function to resolve/enable them. This resolve function will also optionally take in Promise<TData> which will populate the query cache before enabling, effectively simplifying the process of streaming the query data from the server(#22). Basically, this would look something like this:

<script lang="ts">
import { trpc } from '$lib/trpc/client';
import type { PageData } from './$types';

export let data: PageData;

const api = trpc();
const query = api.greeting.createQuery('normal');
const [lazyQuery, resolveLazyQuery] = api.greeting.createQuery('lazy', { lazy: true });
const [streamedQuery, resolveStreamedQuery] = api.greeting.createQuery('streamed', { lazy: true });
</script>

<!-- Regular query -->
<div>
  {#if $query.isLoading}
    Loading...
  {:else if $query.isError}
    Error: ${query.error}
    {:else}
    {$query.data}
  {/if}
</div>

<!-- Query only enabled on button press -->
<div>
  {#if $lazyQuery.isLoading}
    Loading...
  {:else if $lazyQuery.isError}
    Error: ${lazyQuery.error}
  {:else}
    {$lazyQuery.data}
  {/if}
  <button on:click={() => resolveLazyQuery()}>Enable lazy query</button>
</div>

<!-- Query with data streamed from +page.server.ts -->
{#await resolveStreamedQuery(data.streamedData)}
  Awaiting...
{:then}
  {#if $streamedQuery.isLoading}
    Loading...
  {:else if $streamedQuery.isError}
    Error: ${streamedQuery.error}
  {:else}
    {$streamedQuery.data}
  {/if}
{/await}
vishalbalaji commented 2 months ago

The lazy option was added for createQuery and createInfiniteQuery in #52, but not for createQueries. I am trying to figure out what the best way to set the query data for each of these queries would be and will implement it in a future update.