A reactive wrapper for PocketBase collections and records in SvelteKit, allowing automatic updates and reactivity.
Ensure you have pocketbase
installed:
npm install pocketbase
Then, add the wrapper files to your SvelteKit project.
pocketbase.svelte.ts
provides a reactive user store and PocketBase instance. The PocketBase URL should be set via an environment variable:
export const pb = new PocketBase(process.env.POCKETBASE_URL);
Additionally, user.current
is a reactive store that holds the current authenticated user.
import { pb, user } from '$lib/pocketbase/pocketbase.svelte.js';
You can authenticate users:
const login = async () => {
const auth = await pb.collection('users').authWithPassword('[email protected]', 'password');
console.log(auth);
};
const logout = async () => {
user.logout();
};
Use CollectionList<T>
to track a collection reactively, where T
is the type of the record.
import { CollectionList } from '$lib/pocketbase/CollectionList.svelte.js';
type TestRecord = { id: string; content: string };
const test = new CollectionList<TestRecord>({
name: 'test',
onInit: async (collection) => await collection.getFullList(),
onUpdate: (record) => ({ ...record, updated: true }),
onCreate: (record) => ({ ...record, new: true }),
onDelete: (record) => console.log(`Record deleted: ${record.id}`)
});
Render in a Svelte component:
<ul>
{#each test.records as record}
<li>{record.id}</li>
{/each}
</ul>
const createTest = async () => {
await pb.collection('test').create({ content: 'test ' + Math.random() });
};
Use CollectionRecord<T>
to track a single record reactively, where T
is the type of the record.
import { CollectionRecord } from '$lib/pocketbase/CollectionRecord.svelte.js';
type TestRecord = { id: string; content: string };
const record = new CollectionRecord<TestRecord>({
name: 'test',
recordId: '119p42gj5817e6u',
onInit: async (collection) => await collection.getOne('119p42gj5817e6u'),
onUpdate: (record) => ({ ...record, modified: true }),
onCreate: (record) => ({ ...record, initialized: true }),
onDelete: (record) => console.log(`Record ${record.id} deleted`)
});
Render in a Svelte component:
<p>Record Content: {record.record?.content}</p>