Skip to content

feat: add Svelte support #91

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/khaki-ties-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@tanstack/svelte-db": patch
---

Add Svelte support

Usage example:

```svelte
<script lang="ts">
import { useLiveQuery } from "@tanstack/svelte-db"
import { todoCollection } from "$lib/collections"

const query = useLiveQuery((query) =>
query.from({ todoCollection }).where("@completed", "=", false)
)
</script>


<List items={query.data} />
```
24 changes: 24 additions & 0 deletions packages/svelte-db/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
node_modules

# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
/dist

# OS
.DS_Store
Thumbs.db

# Env
.env
.env.*
!.env.example
!.env.test

# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
3 changes: 3 additions & 0 deletions packages/svelte-db/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @tanstack/svelte-db

Svelte hooks for TanStack DB. See [TanStack/db](https://github.com/TanStack/db) for more details.
47 changes: 47 additions & 0 deletions packages/svelte-db/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "@tanstack/svelte-db",
"description": "Svelte integration for @tanstack/db",
"version": "0.0.0",
"scripts": {
"build": "svelte-package --input ./src --output ./dist",
"test": "npx vitest --run",
"lint": "eslint . --fix"
},
"files": [
"dist",
"!dist/**/*.test.*",
"!dist/**/*.spec.*"
],
"sideEffects": [
"**/*.css"
],
"svelte": "./dist/index.js",
"types": "./dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"svelte": "./dist/index.js"
}
},
"dependencies": {
"@tanstack/db": "workspace:*",
"@tanstack/svelte-store": "^0.7.0"
},
"peerDependencies": {
"svelte": "^5.0.0"
},
"devDependencies": {
"@sveltejs/package": "^2.3.11",
"@vitest/coverage-istanbul": "^3.0.9",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"publint": "^0.3.2",
"svelte": "^5.28.6",
"svelte-check": "^4.2.0"
},
"keywords": [
"optimistic",
"svelte",
"typescript"
]
}
10 changes: 10 additions & 0 deletions packages/svelte-db/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Re-export all public APIs
export * from "./useOptimisticMutation.js"
export * from "./useLiveQuery.svelte.js"

// Re-export everything from @tanstack/db
export * from "@tanstack/db"

// Re-export some stuff explicitly to ensure the type & value is exported
export { Collection } from "@tanstack/db"
export { createTransaction } from "@tanstack/db"
58 changes: 58 additions & 0 deletions packages/svelte-db/src/useLiveQuery.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { useStore } from "@tanstack/svelte-store"
import { compileQuery, queryBuilder } from "@tanstack/db"
import type {
Collection,
Context,
InitialQueryBuilder,
QueryBuilder,
ResultsFromContext,
Schema,
} from "@tanstack/db"

export interface UseLiveQueryReturn<T extends object> {
state: Map<string, T>
data: Array<T>
collection: Collection<T>
}

export function useLiveQuery<
TResultContext extends Context<Schema> = Context<Schema>,
>(
queryFn: (
q: InitialQueryBuilder<Context<Schema>>
) => QueryBuilder<TResultContext>,
deps: Array<() => unknown> = []
): UseLiveQueryReturn<ResultsFromContext<TResultContext>> {
const compiledQuery = $derived.by(() => {
// Just reference deps to make derived reactive to them
deps.forEach((dep) => dep())

const query = queryFn(queryBuilder())
const compiled = compileQuery(query)
compiled.start()
return compiled
})

const state = () => useStore(compiledQuery.results.derivedState).current
const data = () => useStore(compiledQuery.results.derivedArray).current
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally tried to use a $derived function here, but useStore for some reason is not reactive. This is still valid usage.

Copy link

@MAST1999 MAST1999 May 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same problem in Solid, I think if we want it to work useStore needs to receive a function otherwise the signal/rune for compiledQuery is not registered in useStore.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I updated it to not use useStore for now. I think as long as the tests pass then we're good 👍🏼

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests may pass but the value will not be reactive, which may cause the component not to update.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you seen the updated code? What do you think about it?

So this means all tanstack store packages needs to be updated then?


$effect(() => {
return () => {
compiledQuery.stop()
}
})

return {
get state() {
return state()
},
get data() {
return data()
},
get collection() {
return compiledQuery.results as unknown as Collection<
ResultsFromContext<TResultContext>
>
},
}
}
15 changes: 15 additions & 0 deletions packages/svelte-db/src/useOptimisticMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createTransaction } from "@tanstack/db"
import type { Transaction, TransactionConfig } from "@tanstack/db"

export function useOptimisticMutation(config: TransactionConfig) {
return {
mutate: (callback: () => void): Transaction => {
const transaction = createTransaction(config)
transaction.mutate(callback)
return transaction
},
createTransaction: (): Transaction => {
return createTransaction({ ...config, autoCommit: false })
},
}
}
7 changes: 7 additions & 0 deletions packages/svelte-db/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"

const config = {
preprocess: vitePreprocess(),
}

export default config
Loading
Loading