Best practice subscription/observable in sveltekit #9070
Unanswered
tobiasBora
asked this question in
Q&A
Replies: 1 comment 2 replies
-
|
Hi, I guess you've set up the PouchDB instance in "./db" (I do it similar) and you're familiar with Svelte 5 runes. Since you have just a listener for a collection, it's very straight forward: <script>
import { db } from "./db";
import { onDestroy } from 'svelte';
let friends = $state([]);
const friendSelector = { kind: 'friend' };
// Fill friends array
db.find({ selector: friendSelector })
.then(result => { friends = result.docs });
// wait and apply changes to friends array
let listener = db.changes({
live: true,
since: 'now',
selector: friendSelector
})
.on('change', (change) => {
// search for a known friend
const i = friends.findIndex((v) => v._id === change.id)
// is it deleted and in the array?
if (change.deleted && i > -1)
// remove it
friends.splice(i, 1);
// is it in the array, has a doc and the doc has a higher revision?
else if (i > -1 && change.doc && change.doc._rev > friends[i]._rev)
// replace it with the new doc
friends[i] = change.doc;
// if it's an unknown doc:
else if (!change.deleted && change.doc)
// append it
friends.push(change.doc);
})
.on('complete', (info) => {
console.warn('live listener exited', info);
friends = [];
})
.on('error', (err) => {
console.error("something's wrong with your friends", err);
friends = [];
});
// clean up
onDestroy(() => {
listener.cancel();
});
</script>
<ul>
{#each friends as friend (friend.id)}
<li>{friend.name}, {friend.age}</li>
{:else}
<li>no friends found</li>
{/each}
</ul> |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I've been a happy Dexie user but I'm now interested in pouchdb for it's easy synchronisation with an external database. But I struggle to understand how I should use it with sveltekit (svelte 5 ideally). This old document https://pouchdb.com/2015/02/28/efficiently-managing-ui-state-in-pouchdb.html mentions quite complicated ways to deal with states (I never needed to implement my own binary search in dexie!), and the fact that I need to use multiple functions to fetch the data a first time before handling changes is quite tedius. So what would be the recommended equivalent of Dexie's code?
Beta Was this translation helpful? Give feedback.
All reactions