<script type="module">
import svelteApollo from 'https://cdn.skypack.dev/svelte-apollo';
</script>
README
svelte-apollo
Svelte integration for Apollo GraphQL.
Example
The following simple example shows how to run a simple query with svelte-apollo.
<!-- App.svelte -->
<Books />
<script>
import { ApolloClient } from "@apollo/client";
import { setClient } from "svelte-apollo";
import Books from "./Books.svelte";
// 1. Create an Apollo client and pass it to all child components
// (uses svelte's built-in context)
const client = new ApolloClient({
/* ... */
});
setClient(client);
</script>
<!-- Books.svelte -->
<script>
import { query } from "svelte-apollo";
import { GET_BOOKS } from "./queries";
// 2. Execute the GET_BOOKS GraphQL query using the Apollo client
// -> Returns a svelte store of promises that resolve as values come in
const books = query(GET_BOOKS);
</script>
<!-- 3. Use $books (note the "
quot;), to subscribe to query values -->
{#if $books.loading}
Loading...
{:elseif $books.error}
Error: {$books.error.message}
{:else}
{#each $books.data.books as book}
{book.title} by {book.author.name}
{/each}
{/if}
Query an Apollo client, returning a readable store of result values.
Uses Apollo's watchQuery,
for fetching from the network and watching the local cache for changes.
If the client is hydrating after SSR, it attempts a readQuery to synchronously check the cache for values.
<script>
import { query } from "svelte-apollo";
import { GET_BOOKS } from "./queries";
const books = query(GET_BOOKS, {
// variables, fetchPolicy, errorPolicy, and others
});
function reload() {
books.refetch();
}
</script>
<ul>
{#if $books.loading}
<li>Loading...</li>
{:elseif $books.error}
<li>ERROR: {$books.error.message}</li>
{:else}
{#each $books.data.books as book (book.id)}
<li>{book.title} by {book.author.name}</li>
{/each}
{/if}
</ul>
<button on:click="{reload}">Reload</button>
Reactive variables are supported with refetch:
<script>
import { query } from "svelte-apollo";
import { SEARCH_BY_AUTHOR } from "./queries";
export let author;
let search = "";
const books = query(SEARCH_BY_AUTHOR, {
variables: { author, search },
});
// `books` is refetched when author or search change
$: books.refetch({ author, search });
</script>
Author: {author}
<label>Search <input type="text" bind:value="{search}" /></label>
<ul>
{#if $books.loading}
<li>Loading...</li>
{:elseif $books.error}
<li>ERROR: {$books.error.message}</li>
{:elseif $books.data}
{#each $books.data.books as book (book.id)}
<li>{book.title}</li>
{/each}
{:else}
<li>No books found</li>
{/if}
</ul>