Hello! I am a little lost on how use the different parts of Yjs together to create an app. I am trying to make a note app that will store each note as a subdoc. I have it set up so that I can create docs and show them in a list, but I cannot figure out how to get data from the subdocs to show in the list.
For example, I want to be able to show the value of ‘title’ from the map ‘fields’ in my code. Right now, I have the buttons for each doc set up to show the JSON of the doc when clicked. When I first create the doc, it shows the values from the map, but if I reload, it is undefined. So I think I’m getting something out of order.
Here is my code (using Svelte):
<script>
import { browser } from '$app/env'
import { IndexeddbPersistence } from 'y-indexeddb'
import * as Y from 'yjs'
import { v1 as uuidv1 } from 'uuid'
let documentList
let myList
let ydoc
if(browser) {
ydoc = new Y.Doc()
documentList = ydoc.getMap('doc-list')
const persistence = new IndexeddbPersistence('database', ydoc)
persistence.on('synced', (e) => { console.log(e) })
ydoc.on('subdocs', (e) => {
console.log(e)
e.added.forEach(subdoc => {
subdoc.load()
const persistence = new IndexeddbPersistence(subdoc.guid, subdoc)
})
})
documentList.observe( ( event => myList = Object.entries(documentList.toJSON() ) ) )
}
const createDoc = () => {
const id = uuidv1()
const newDoc = new Y.Doc()
const fields = newDoc.getMap('fields')
fields.set('title', `Doc ${Math.floor(Math.random() * 100)}`)
documentList.set(id, newDoc)
}
</script>
<div>
<button on:click={ ()=> createDoc() }>New Doc!</button>
{#if myList}
<h1>Test</h1>
<ul>
{#each myList as [key, value]}
<li>
<button on:click={ ()=> console.log(documentList.get(key).toJSON() ) }>{key}</button>
</li>
{/each}
</ul>
{/if}
</div>
I appreciate any help to get me unstuck!