4

Does this function duplicate results as a bug or am I causing this? The output always has 1 or more records duplicated. In this example, Bank of China is always listed twice in output.

gun.get('savings_accounts').map(function (name, ID) {
    console.log( name.name, ID );
}, true)

My code:

localStorage.clear();
var gun = Gun();

////////////////////////////////////////////////////// create record
var acc1 = gun.put({
    name: "Bank of America",
    accType: "Savings",
    last4: "4123",
    favorite: true,
    status: true,
    created: "some date created"
    });
var acc2 = gun.put({
    name: "Bank of China",
    accType: "Savings",
    last4: "5123",
    favorite: true,
    status: true,
    created: "some date created"
    });

gun.get('savings_accounts').map(function (name, ID) {
    console.log( name.name, ID );
}, true)
riQQ
  • 9,878
  • 7
  • 49
  • 66
jtlindsey
  • 4,346
  • 4
  • 45
  • 73

1 Answers1

6

From the author of GunDB, Mark Nadal

1) gun.get('savings_accounts').map().val(cb) is what you want for normal / procedural / easy things. HOWEVER...

2) gun is actually functional/reactive (FRP), or also known as streaming/event oriented. The data might/will get called multiple times (if you don't use .val) because A) in-memory replies, B) your browser's localStorage replies, C) the server will reply, D) server will relay to other browser peers which each might reply with data. ^ that is the "realtime" part of gun.

.val only fires once (well per item on the chain, so if you do map().val(cb) the val will get fired multiple times but only once from each item in the list).

use .val(cb) if you are doing procedural things.

Use .on(cb) (which is what .map(cb) uses internally. Most API methods internally use .on) if you want to subscribe to realtime updates of the data. you'll slowly find that the realtime/FRP/event/streaming as being a much cleaner way to write your apps.

jtlindsey
  • 4,346
  • 4
  • 45
  • 73