How do I update an array?

import * as Y from ‘yjs’
const ydoc = new Y.Doc()
const yarray = ydoc.getArray(‘my array type’)
const yarrayNested = new Y.Array()
yarray.set(‘my nested array’, yarrayNested)
yarray.insert(0, [1, 2, 3]) // insert three elements

Then How can I do this in one step
yarray.delete(1, 1) // delete second element
yarray.insert(1,[2]) // update

Hi @snailsdream,

When you say “in one step”, do you mean that you want to write only one statement to change the array, or that you want the two changes to happen atomically?

If you want to use methods like Array.prototype.splice, check out GitHub - YousefED/SyncedStore: SyncedStore CRDT is an easy-to-use library for building live, collaborative applications that sync automatically. by @YousefED which lets you use familiar methods like splice while still getting Y.js synchronization “under the hood”.

If you want the two changes to happen atomically, you can bundle their changes together inside a doc.transact(() => { /* multiple changes here */ }). You can read some details or caveats about atomicity in this thread Transactions: atomicity and labeling? - #4 by jasonm

I hope this helps!

1 Like

Thank you, This helped me a lot