An open API service indexing awesome lists of open source software.

https://github.com/wobsoriano/svelte-instantdb

Unofficial Instant SDK for Svelte
https://github.com/wobsoriano/svelte-instantdb

svelte

Last synced: 6 months ago
JSON representation

Unofficial Instant SDK for Svelte

Awesome Lists containing this project

README

          

# svelte-instantdb

Unofficial [Instant](http://instantdb.com/) SDK for Svelte 5.

## Installation

```bash
npm install svelte-instantdb
```

## Usage

### Reading and Writing Data

```svelte

import { init, tx, id } from 'svelte-instantdb';

const db = init({
appId: '__YOUR_APP_ID__'
});

const query = db.useQuery({ messages: {} });

const addMessage = (message) => {
db.transact(tx.messages[id()].update(message));
};

{#if query.current.isLoading}

Fetching data...

{:else if query.current.error}
Error fetching data: {query.current.error.message}

{:else}

{/if}
```

### Cursors

```svelte
Move your cursor around! ✨
```

Custom cursors

```svelte

Move your cursor around! ✨

{#snippet cursor({ color, presence })}

{/snippet}

```

### Typing indicator

```svelte

// Init schema and db
// ...

const room = db.room('chat', 'main');

// 1. Publish your presence in the room
const presence = room.usePresence({
peers: [],
user: false
});

onMount(() => {
presence.current.publishPresence({ name: 'your_username' });
});

// 2. Use the typing indicator
const typing = room.useTypingIndicator('chat');

function typingInfo(users) {
if (users.length === 0) return null;
if (users.length === 1) return `${users[0].name} is typing...`;
if (users.length === 2) return `${users[0].name} and ${users[1].name} are typing...`;

return `${users[0].name} and ${users.length - 1} others are typing...`;
}





{typing.current.active.length ? typingInfo(typing.current.active) : <> >}



```

### Reactive variables

To make functions return reactive state, pass a function that returns a state instead:

```ts
let todoId = $state(null);

const todoState = db.useQuery(() =>
todoId
? {
todos: {
$: {
where: {
id: todoId
}
}
}
}
: null
);

todoId = 'some_id';
```

## License

MIT