'How to redirect in Nuxtjs when the return query of Graphql is empty

I'm very new to Nuxtjs and javascript world. The Nuxtjs project I'm working on required fetching data from Backend (Strapi) using Graphql. The goal is to make a redirect to homepage (index.vue) when Graphql return empty query result. However, it did not work when I'm using router.push('/') as the code below.

Please note that I'm trying to redirect both on result and mounted block. Both of them did not work at all.

Please help me point out what I'm doing wrong here. Thank you for your kindness in advance

<script>
import getProfiletQuery from '~/apollo/queries/profiles/profile'

export default {
  data () {
    return {
      profiles: {
      }
    }
  },
  apollo: {
    profiles: {
      prefetch: true,
      query: getProfiletQuery,
      variables () {
        return { user: this.$route.params.user }
      },
      result ({ data }) {
        if (data.profiles.length === 0) {
          console.log('it enters here!!!')
          this.$router.push('/') //this is not working
        }
      }
    }
  },
  mounted () {
    console.log('this.profiles.length: ', this.profiles.length)
    if (this.profiles.length === 0) {
      this.$router.push('/')
    }
  }
}
</script>


Solution 1:[1]

Old question, but the replies weren't helpful at all and no answers were offered. So in case you never found the answer, here's the best way I know of personally.

The reason your intended method didn't work is because it's unexpected behaviour for the Nuxt router. This is explained in much more detail here: vue-router — Uncaught (in promise) Error: Redirected from "/login" to "/" via a navigation guard

There are some possible workarounds listed there, but don't use them in this use case.

What you want to do instead, is throw an error, then let Nuxt's built-in error handling take over.

Inside your result(), you need to properly call a Nuxt error like so:

result ({ data }) {
  if (data.profiles.length === 0) {
    this.$nuxt.error({ statusCode: 404, message: 'Page not found.' })
  }
}

Then, you will need to ensure you have an error.vue template file inside your /layouts/ directory. This should contain at a bare minimum:

<template>
  <div class="container">
    <h1>{{ error.statusCode }}</h1>
    <h2>{{ error.message }} </h2>
  </div>
</template>

Sorry I didn't see this earlier, and hope you got something working in the meantime! At least now there is an answer there for whoever comes looking next!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Halliday