vuejs / vue-hackernews-2.0

HackerNews clone built with Vue 2.0, vue-router & vuex, with server-side rendering
MIT License
10.96k stars 2.15k forks source link

Redirect at component level #282

Closed BorjaRafols closed 6 years ago

BorjaRafols commented 6 years ago

So I'm having lots of troubles setting the app up for this use case.

I haave the following routes:

{
   path: '/404*', component: NotFound, name: 'not-found',
 },
{
   path: '/:blogSlug', component: BlogPost, name: 'blog-post',
 },
{
   path: '/*', component: NotFound, name: 'default',
 }

Now on my BlogPost component, in the asyncData function I do this, to find the post data.

asyncData({store, route, router}) {
            let slug = route.params.blogSlug

            if (!store.state.blog.posts[slug]) {
                return store.dispatch('FETCH_BLOG_POST', { slug: slug }).catch((error) => {
                    router.push('/404');
                })
            }
            return(Promise.resolve());
        }

The thing is this is not working as expected, and the app is crashing. SSR works, and when navigating to a invalid post name () it shows the 404 page.

However during hydration everything breaks.

How am I suposed to handle these cases, I haven't found any information anywhere.

I've you feel like, I can provide a repo with the sample code.

sirlancelot commented 6 years ago

Try to return rejected promise with a value of { url: '/404' }. Your .catch() function is "handling" the error and resolving the promise.

Replace the router.push() line with this: throw { url: '/404' };. You can also throw an Error, just make sure it has a url prop pointing to the URL of your choice.

entry-server.js@19 shows an example of this. Since you're attempting to do a redirect during the asyncData phase, you need to create your own rejected Promise.

BorjaRafols commented 6 years ago

That's just marvelous.

I'll take note and maybe I send my first PR to update the docs. This should be explicitly explained in my opinion.

Thanks a lot Sir.

sirlancelot commented 6 years ago

There's documentation for this repo? I thought it was just a small demo...

PS: Be sure to close this issue if you feel it's resolved :tada:

BorjaRafols commented 6 years ago

I was talking about the main VueJS docs.

Anyway, I'm closing this issue.