How to make Blaze templates reactive


#1

I’m populating a template with data using Blaze.renderWithData(), but how can you make it reactive so when the underlying data changes, it is reflected in the template reactively. This is how the template is rendered with data:

var myContainer = document.getElementById('myContainer');
var keyImg = $(event.currentTarget).closest('.shadow').find('.imgRef').val();
var keyUser = $(event.currentTarget).closest('.shadow').find('.imgRef1').val();

Meteor.call('getDetailsUser',keyImg,keyUser, function(err,result){
    if(err){
        console.log(err.reason);
        return;
    }

    Blaze.renderWithData(Template.see,result,myContainer);
});



getDetailsUser: function(key,user){
    if(Meteor.user()){
        getUser = Meteor.users.findOne({$and:
            [{_id: user}, {'ImagesUploaded.key':key}]
        });

        getUser.ImagesUploaded.forEach(function (items)
        {
            if (items.key===key){
                image = items;
            }

        });

        return image;
    }
}

Otherwise new data is only displayed on refresh.


#2

You want to render the template just once, and then just reactively update it’s data. So something like:

var userDetails = new ReactiveVar();
var userDetailsContext = function() { return userDetails.get() };
Blaze.renderWithData(Template.see, userDetailsContext, myContainer);

Meteor.call('getDetailsUser', keyImg, keyUser, (err, result) => {
  // if (err) ...
  userDetails.set(result);
});

Does it make sense?

If you’re comfortable with it, instead of defining a userDetailsContext you could simply use userDetails.get.bind(userDetails).


#3

Thanks

I tried that but it still did not provide reactivity.


#4

If you can share the code on github I’ll take a quick look.


#5

Thanks

Here’s the link


#6

I meant the whole repo but I stubbed it at https://github.com/gadicc/repro-ranjeev. The reactivity seems to work fine :slight_smile:


#7

Thanks :slight_smile:


#8

@gadicc: I know it’s been a while since you posted it, but your solution was really helpful to a problem I was struggling with this morning. Thanks!