How do I increment and decrement?

I want increment a value,What can I do?

import * as Y from ‘yjs’
const ydoc = new Y.Doc()
const ymap = ydoc.getMap()
ymap.set(‘keyA’, 0)
const ydocRemote = new Y.Doc()
const ymapRemote = ydocRemote.getMap()
ymapRemote.set(‘keyA’, 0)
// I except
ymapRemote.incr(‘keyA’, 2)
const update = Y.encodeStateAsUpdate(ydocRemote)
Y.applyUpdate(ydoc, update)
console.log(ymap.toJSON()) // => { keyA: 2 }

There are a few ways to do this, one of them is shown in the yjs readme here: GitHub - yjs/yjs: Shared data types for building collaborative software

1 Like

Thank you,but I can not find the way.

@snailsdream The example that BitPhinix linked to does indeed implement incr/decr, but perhaps not quite the way you might expect. It looks like there aren’t incr/decr primitive actions in Y.js, but you can create the same behavior using a Y.Array which contains a list of the incr/decr values as integers, and then summing the items of the array when you want to observe the count. See the “array of numbers which produce a sum” comment in the example linked above.

2 Likes

Thank you very much, I got it