orbitdb / field-manual

The Offical User's Guide to OrbitDB
207 stars 43 forks source link

Fixed counter example - tutorial/ch3 #142

Closed tjbdev closed 3 years ago

tjbdev commented 3 years ago

If I run this

async function main(){
    const NPP = require('./newpieceplease');
    await NPP.create();

    const piece = NPP.getPieceByHash("QmNR2n4zywCV61MeMLB6JwPueAPqheqpfiA4fLPMxouEmQ");
    await NPP.getPracticeCount(piece).then(console.log);
    const cid = await NPP.incrementPracticeCounter(piece);
    await NPP.getPracticeCount(piece).then(console.log);
}

main()

The first time, the output is:

0
1

But the second time, after the database is already created, the output is

1
1

So, I go into node and try some stuff and I find that if you "open" the database with orbitdb.counter(counter.id), then the value resets:

> const NPP =  require('./newpieceplease')
undefined
> NPP.create()
Promise { <pending> }
> let counter = NPP.orbitdb.counter("test")
undefined
> counter = counter.then(a=>counter=a)
Promise { <pending> }
> let id = counter.id
undefined
> id
'/orbitdb/zdpuAxHhs9pXv7yjEafjvXpLMkUM9dcVVS2JkaS29BYSP3qUE/test'
> counter.value
0
> counter.inc()
Promise { <pending> }
> counter.value
1
> counter = NPP.orbitdb.counter(id)
Promise { <pending> }
> counter = counter.then(a=>counter=a)
Promise { <pending> }
> counter.value
0

The manual says:

await this.orbitdb.counter(piece.counter) is a new way of using this.orbitdb.counter, by passing in an existing database address. This will open the existing database instead of creating it

I found that if you do the same but load() it seems to work, (adding to the previous node terminal state):

> counter.inc()
Promise { <pending> }
> counter.value
1
> counter = NPP.orbitdb.counter(id)
Promise { <pending> }
> counter = counter.then(a=>counter=a)
Promise { <pending> }
> counter.load()
Promise { <pending> }
> counter.value
1

Notice how after counter = NPP.orbitdb.counter(id) and also counter.load() the value did not reset to 0 as it did previously, but was retained.

Just a problem I noticed following the tutorial, but if I am wrong please let me know, I'm trying to learn :)