SvelteStack / svelte-query

Performant and powerful remote data synchronization for Svelte
https://sveltequery.vercel.app
MIT License
813 stars 31 forks source link

Custom hooks? #64

Closed vaclavgreif closed 2 years ago

vaclavgreif commented 2 years ago

I'm coming from the React SWR, where I can create a hook like this:

function useUser (id) {
  const { data, error } = useSWR(`/api/user/${id}`, fetcher)

  return {
    user: data,
    isLoading: !error && !data,
    isError: error
  }
}

and then use it in my components like this:

function Avatar ({ id }) {
  const { user, isLoading, isError } = useUser(id)

  if (isLoading) return <Spinner />
  if (isError) return <Error />
  return <img src={user.avatar} />
}

Is something like the possible with Svelte Query? I tried a manual subscription to the useQuery, which doesn't seem to trigger the re-render though.

SomaticIT commented 2 years ago

Hello,

It's not exactly the same way. svelte-query use svelte's stores internally.

You can use the derived store to create custom "hooks":

import { derived } from "svelte/store";

export function useUser(id) {
  const store = useQuery(`/api/user/${id}`, fetcher);
  return derived(store, ({ data, ...$store }) => ({
    user: data,
    ...$store
  });
}

Then, you can use it in you Svelte components:

<script>
  import { useUser } from "$lib/api/user";
  const userQuery = useUser(userId);
</script>

{#if $userQuery.isLoading}
  <Spinner />
{:else if $userQuery.isError}
  <Error error={$userQuery.error} />
{:else}
  <UserItem user={$userQuery.user} />
{/if}
vaclavgreif commented 2 years ago

Very cool, thanks, I didn't know about the derived stores!