MetaSean
MetaSean

Reputation: 951

Getting streaming data from gun

on() is supposed to stream data from a path or key 1. But when I put data on my path, I'm not seeing the updated stream.

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on();
myData.put({hello:'world'});

Upvotes: 2

Views: 267

Answers (2)

Stef de Vries
Stef de Vries

Reputation: 109

Update: since Gun v0.391 using val() also requires a callback. The automatic logging is no longer provided.

Upvotes: 1

marknadal
marknadal

Reputation: 7624

.on() is an asynchronous function, so you need to update your code to look like this:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on(function(data){
    console.log("update:", data);
});
myData.put({hello:'world'});

Hope that helps!


If you are new to programming, "anonymous functions" (often times called a callback) in the above code can be somewhat confusing. The above code can also be rewritten to this, which has the exact same behavior:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');

var cb = function(data){
    console.log("update:", data);
};

myData.on(cb);

myData.put({hello:'world'});

For debugging purposes, there is also a .val() convenience function that will automatically log data for you:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on().val()
myData.put({hello:'world'});

However it is intended for one off purposes, not for streaming. Just as a note, you can pass .val(function(data){}) a callback which will override the default convenience logger.

Upvotes: 2

Related Questions