Skip to content

RobertoSnap/zero-svelte-query

Repository files navigation

NPM Version NPM Unpacked Size NPM Downloads

zero-svelte-query

A Svelte library for integrating @rocicorp/zero with Svelte applications. Provides reactive query bindings and store integration for real-time data synchronization.

Features

  • ✨ Reactive query subscriptions
  • 🔄 Lightweight and minimalistic
  • ⚡️ Nice dev tools

Installation

From NPM

npm install zero-svelte-query
# or
pnpm add zero-svelte-query
# or
yarn add zero-svelte-query

Usage

See real examples in src/routes

Basic Query Example

<script lang="ts">
	import { useQuery } from 'zero-svelte-query';
	import { getZero } from '$lib/zero'; // Update to standard SvelteKit path

	const zero = getZero();
	const tags = useQuery(zero.query.tag); // Use const instead of let
</script>

{#if $tags?.current}
	{#each $tags.current as tag (tag.id)}
		<p>{tag.name}</p>
	{/each}
{/if}

Zero Store Configuration

Initialize Zero in your application setup. Here's a basic implementation example:

zero.state.svelte.ts // ... rest of existing code ...

import { schema, type Schema } from '$zero/schema';
import { Zero, type ZeroOptions } from '@rocicorp/zero';
import { get, writable } from 'svelte/store';

export const zeroStore = writable<Zero<Schema> | null>(null);

export const setZeroStore = (_options: Partial<ZeroOptions<Schema>>) => {
	const options = {
		schema,
		kvStore: "mem",
		logLevel: "debug",
		..._options,
	} as ZeroOptions<Schema>;
	zeroStore.set(new Zero(options));
}

export const getZero = () => {
	const z = get(zeroStore);
	if (!z) {
		throw new Error('Zero not initialized');
	}
	return z;
}

Then use it in for example a +layout.svelte file

setZeroStore({
    server: 'http://localhost:5949',
    auth: token || undefined,
    userID: userId || 'anon'
});

Development

Setup

# Install dependencies
pnpm install

# This will start a testcontainer with zero-cache, postgres and a vite svelte-kit application.
pnpm dev

# Run tests
pnpm test

# Run only unit tests
pnpm test:unit

# Run only e2e tests
pnpm test:e2e

Scripts

  • pnpm dev - Starts both backend and frontend development servers
  • pnpm build - Builds the package for production
  • pnpm schema - Builds the Zero schema
  • pnpm db:generate - Generates database files using Drizzle Kit

License

Apache 2.0

Contributing

Dont know yet

Learning

This library is a lightweight createSubscriber wrapper around the zero instance. You could basically just copy this file useQuery.svelte.ts and use it in your project.

Alternatives

zero-svelte (npm) offers additional caching features and more advanced query management.

Versions

@rocicorp/zero drizzle-zero-svelte @rocicorp/zero spesific
^0.12.0 ^ 0.2.0 0.12.2025012501
^0.11.0 ^ 0.1.0 0.11.2025011402

Credits