Live lists
A list of notes can update straight away when a note is added, edited or deleted, on any device. This example continues from Private notes, in the same REPL.
Run it
Listen to the notes, printing their titles newest first each time they change:
let latest = 0
const show = async notes => {
const run = ++latest
const newest = Object.values(notes ?? {})
.filter(note => note?.title && note.created)
.sort((a, b) => b.created - a.created)
const titles = await Promise.all(
newest.map(note => holster.SEA.decrypt(note.title, user.is)),
)
if (run === latest) console.log(titles)
}
user.get("notes").on(show, true, {nested: true})
// ["Groceries"]Add a note, and the list prints again:
const second = crypto.randomUUID()
await user
.get("notes")
.next(second)
.put({
title: await holster.SEA.encrypt("Ideas", user.is),
body: await holster.SEA.encrypt("Learn the cello", user.is),
created: Date.now(),
})
// ["Ideas", "Groceries"]Delete it, and it's gone from the next list:
await user.get("notes").next(second).put(null)
// ["Groceries"]To stop listening, pass the same callback to off():
user.get("notes").off(show)How it works
{nested: true}: each note is an object, stored as its own node. Without this option, editing a note's title wouldn't notify a listener onnotes, since nothing on that node itself changed. See on.The whole list each time: the callback receives every note, not just the one that changed, so it builds the list from scratch rather than keeping track of changes.
Skipping incomplete notes: a change can arrive in parts, so the list may print more than once. A new note can show up before its
createdtime, and deleting a note sets each of its properties tonullbefore the note itself. Thefilterskips any note without atitleandcreated, which also covers deleted notes.Only the newest update is shown: decrypting titles takes time, so updates that arrive close together can finish out of order. Each call takes a number from
latest, and only the newest prints, so an older list can't replace a newer one.