AstroJS-SvelteQuery Svelte Themes

Astrojs Sveltequery

This made me a better Web developer

Integrating Svelte Query with Astro

This repo demonstrates how to use TanStack Query (Svelte Query) with Astro - something that isn't as straightforward as you might expect due to how Astro's island architecture works.

The Problem

When trying to use Svelte Query with Astro, you'll likely run into this error:

Error: No QueryClient was found in Svelte context. Did you forget to wrap your component with QueryClientProvider?

This happens because Astro's islands are isolated JavaScript contexts, and Svelte's context API doesn't work across them.

Our Solution

We solved this by creating wrapper components that keep the QueryProvider and query components together in the same island:

Astro Page
└── Wrapper Component (client:only="svelte")
    ├── QueryProvider
    └── Data Component (uses createQuery)

Visual Explanation

Here's a diagram showing how components are structured in this pattern:

Key Components

  • QueryProvider.svelte - Sets up the QueryClient
  • QueryRoot.svelte - Combines the provider with the Posts component
  • PostRoot.svelte - Combines the provider with the individual Post component

How It Works

  1. Each Astro page imports its own wrapper component
  2. The wrapper includes both the provider and data component
  3. We use client:only="svelte" on the wrapper, not individual components
  4. This keeps the context chain intact within each island

Getting Started

To use this pattern in your own project:

  1. Create a base QueryProvider component
  2. Create wrapper components for each major data need
  3. Use these wrappers in your Astro pages with client:only="svelte"
  4. Handle dynamic routes with either:
    • getStaticPaths() for known routes
    • export const prerender = false for SSR (requires setup)

Why This Works

Astro's partial hydration creates isolated "islands" of interactivity. Svelte's context API can only share context within a component tree, not across islands.

By wrapping related components together, we keep everything that needs to share context in the same island.

Scaling Tips

  • Organize by domain - Create wrappers for different sections of your app
  • Consistent query keys - Use prefixes like ['posts'], ['post', id]
  • Optimize performance - Set appropriate staleTime and cacheTime values
  • Consider persistence - Add storage persistence for better UX

Learn More

Top categories

Loading Svelte Themes