Matt
Matt

Reputation: 1632

Difficulty Redirecting to a 404 Page

I'm trying to redirect to a 404 page if the user profile visited does not exist. I'm running an asynchronous created lifecycle hook which checks if the user exists, and if not I use $router.push to push to the 404 page, as shown below:

component.vue

async created() {
    const userExists = await this.$store.dispatch("user/creatorExists", {
        userId: this.$route.params.userId
    });
    if (!userExists) {
        this.$router.push({ name: "pageNotFound" });
    }

The problem is that during the call to check if the user exists or not, component.vue will load fully, so the end user will see the initial component flicker on their screen before being redirected.

Is there a better way to redirect to a 404 page if a user does not exist?

Upvotes: 3

Views: 175

Answers (2)

Phil
Phil

Reputation: 165062

Use a beforeRouteEnter in-component navigation guard

import store from "wherever/your/store/lives"

export default {
  name: "UserProfile",
  async beforeRouteEnter (to, from, next) {
    const userExists = await store.dispatch("user/creatorExists", {
        userId: to.params.userId
    });
    if (!userExists) {
        return next({ name: "pageNotFound" });
    }
    next()
  },
  // data, computed, methods, etc
}

See also Data Fetching - Fetching Before Navigation

Note that there is no access to the Vue component via this within the beforeRouteEnter guard so you'll need to import your store from wherever it is defined.

Upvotes: 1

sugars
sugars

Reputation: 1493

My suggestion is that you should put logic in the global before guards using router.beforeEach

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
 // Check each time before entering the page or a specific page  
})

Upvotes: 1

Related Questions