How to make Blaze templates reactive

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.

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).

1 Like

Thanks

I tried that but it still did not provide reactivity.

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

Thanks

Here’s the link

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

Thanks :slight_smile:

@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!

1 Like