Gemmi
Gemmi

Reputation: 1242

Meteor reactive collection data

I getting bookings/data by the helper:

Template.dashboard.helpers  ({
    getUserBookings: function() {
        _deps.depend();
        var user = Meteor.user();    
        getBookingsClient(user.emails[0]['address'], function(err, res){
            if ( err ) { console.log("Booking get error.");
            } else {
                console.log("Booking get correct.");
                Session.set('bookingResponse', res);
            }
        });    
        return Session.get('bookingResponse') || "";
    }

And in my template:

 {{#if getUserBookings}}
      {{#each getUserBookings}}
          {{bookingName}}
      {{/each}}
 {{/if}}

How I can make this data reactive? I mean when I change for example bookingName in my mongoDB it will immediately change it on website?


Update:

if(Meteor.isClient) {
    getBookingsClient = function (email, callback) {
        Meteor.call('getBookings', email, callback);
    };
}


if(Meteor.isServer) {
    getBookings: function (email) {
        check(email, String);
        var bookings = Bookings.find({'clientDetails.email': email}).fetch();
        return bookings;
    },
}

Upvotes: 1

Views: 378

Answers (2)

Vikk
Vikk

Reputation: 647

Expanding on the answer by Brendan Turner: To get reactivity in Meteor you need to use one of the defined reactive sources or implement one as shown in the docs: Docs.

Anything that results in a Cursor (returned from database query) is reactive. To retrieve Cursors you can use the Publish and Subscribe model as shown. Publish the data you want a client to have access to, and have the code subscribe to retrieve the data.

Template Helpers are reactive computations. If they have reactive data sources, they will be reactive.

Upvotes: 3

Brendan Turner
Brendan Turner

Reputation: 430

You need to publish the booking information from the server and subscribe to it from the client. It might look like this:

// server/publications.js
Meteor.publish('bookingData', function() {
    return Bookings.find({userId: this.userId});
});

// client/template.js
Template.dashboard.helpers({
    userBookings() {
        return Bookings.find({userId: Meteor.userId()});
    }
});

Template.dashboard.onCreated(function() {
    this.subscribe('bookingData');
});

Upvotes: 2

Related Questions