Quantcast
Viewing all articles
Browse latest Browse all 4826

404 when route is known, but model is missing

@ryanto wrote:

I’ve seen a couple different answers floating around the Internet for this situation. Figured I would ask here to get everyone’s current thinking.

I’ve got a router that looks like this.

Router.map(function() {
  this.route('post', { path: '/posts/:post_id' })

  this.route('404', { path: ':wildcard' });
});

And if I visit /this-url-isnt-found then the 404 route correctly displays. Image may be NSFW.
Clik here to view.
:+1:

However, if I visit /posts/this-id-doesnt-exist then my post route tries to render with an empty post. Here’s what the post route looks like:

export default Route.extend({
  model({ post_id }) {
    // there's no server, all posts are stored locally
    return this.store.peekAll('post').findBy('id', post_id);
  }
});

Currently, when the post isn’t found, the template tries to render with a null model.

I’ve currently solved this by using intermediateTransitionTo in the afterModel hook:

export default Route.extend({
  model({ post_id }) {
    // there's no server, all posts are stored locally
    return this.store.peekAll('post').findBy('id', post_id);
  },

  afterModel(post) {
    if (!post) {
      return new Promise(() => {
        this.intermediateTransitionTo('404', { wildcard: '404' });
      });
    }
  }
});

But I could only get this working if I wrapped it in a Promise, and tbh I’m not sure why it works. That made me think that maybe this approach is wrong.

I guess I have two questions:

  1. Is this the best way to handle a known route that has a missing model?
  2. Why does wrapping it in a Promise suddenly make it work?

Thanks!

Posts: 2

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 4826

Trending Articles