When trying to access an attribute, I get TypeError: Cannot read property in the console. But the site is working

When trying to read an attribute, meteor gives me a TypeError: Cannot read property 'featuredImage' of undefined error in the browser console. But it reads featuredImage and the site is working fine. How can I get rid of this error? Is it happening because my subscriptions are not yet ready? Is that’s the case, how to fix it? (PS : Im using the flow router so I can’t wait for subscriptions in the router)

My template code :

Template.About.helpers({
    page: () => {
        return findPage();
    },
    featuredImage: () => {
        var thisPage = findPage();
        return Images.findOne({
            "_id": thisPage.featuredImage
        });
    }
});

function findPage() {
    return Pages.findOne({
        slug: 'about'
    });
}

The router code :

FlowRouter.route('/about', {
    name: 'about',
    subscriptions: function() {
        this.register('page', Meteor.subscribe('pages', 'about'));
        this.register('image', Meteor.subscribe('images'));
    },
    action() {
        BlazeLayout.render('MainLayout', {
            content: 'About'
        });
        setTitle('About Us');
    },
    fastRender: true
});

Try checking the problematic object before using it:

var thisPage = findPage();

if (thisPage) {
 return Images.findOne({
   "_id": thisPage.featuredImage
 });
}

It won’t be defined when the page loads (hence the error), but because it’s in a helper it’ll come through when it’s ready (hence why it works eventually). This change ensures that the query only fires when thisPage is actually ready.

1 Like

Thanks! It also works! I just tried to wrap the code inside if (FlowRouter.subsReady()) and that also works like a charm. You’r correct :smiley:

1 Like