Closed vaclavgreif closed 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}
Very cool, thanks, I didn't know about the derived stores!
I'm coming from the React SWR, where I can create a hook like this:
and then use it in my components like this:
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.