Stéphane R.
Stéphane R.

Reputation: 1496

IronRouter dataNotFound on blog post

I would like show 404 page if blog/xyz don't work. So i've add dataNotFound on my routes.js, but i've no result :

Router.route('/blog/:slug', {
  name: 'blogPost',
  parent: 'blog',
  itemName: function () {
    return this.data().post.title;
  },
  data: function () {

    let post = Posts.findOne({
      'slug': this.params.slug
    });

    return {
      post,
      profil
    };

  }
});

Router.onBeforeAction('dataNotFound', {
  only: 'blogPost'
});

If i test wrong url with blog/ojhojeofje, i don't have 404 page, just post without data.

Do you have any idea ?

Thank you !

Upvotes: 0

Views: 55

Answers (1)

Waiski
Waiski

Reputation: 9680

First of all, you need to register dataNotFound as plugin instead of in onBeforeAction:

Router.plugin('dataNotFound', { only: ['blogPost'] });

Secondly the dataNotFound plugin works by checking if your route data() returns a falsy value. Since you want to load multiple data object in your data() function, you need to alter your function so that it will return something falsy if the post is not found. For example you can simply do this:

data: function () {
  let post = Posts.findOne({
    'slug': this.params.slug
  });
  if (!post) {
    return false;
  }
  ...

Note that you also need to make sure that your subscription to the Posts collection is ready before you run data in order to avoid going to the not found page unnecessarily.

Upvotes: 1

Related Questions