I'm stuck with a loop problem that I think shouldn't have reasons to happen. In a Nuxt nested dynamic page component (_id.vue), I want to check if to.hash is not empty in a beforeRouteLeave navigation guard but when I do this check and it is true, I get RangeError: Maximum call stack size exceeded.

I did a test with console.log('test') and I saw it was called non-stop until the browser stops it before to prevent it to crash.

  beforeRouteLeave (to, from, next) {
    // there is hash and if the user click the back button of the browser, I want to return him to the position of the product file where he was before the click to enter into it
    if (to.name.startsWith('index___') && to.hash !== '') {
      next({ path: to.path, hash: `#${this.$route.params.id}` })
    } else {
      next()
    }
  }

This only happens if I test for to.hash !== '' but not for to.hash === '#ct' and I can't understand why?

If the user comes from the index page with a hash in the path, if he clicks the browser's back button, I want to brings him back to the position in the page where he was when he clicked to browse to the _id page.

Can someone helps me please to understand what's happening here?

Thank you

1

There are 1 best solutions below

0
On

I got an answer that helped me in Vue forum, I didn't know that next() was recalling the process and that my beforeRouteLeave hook was reevaluating the new to.hash I setted causing the loop (to.hash !== '' was always true).

Be sure to test a value to the opposite that will pass the condition after you set it the 1rst time.

here's the code to fix the problem:

  beforeRouteLeave (to, from, next) {
    if (to.name.startsWith('index___') && (to.hash === '#ct' | (to.hash !== `#${this.$route.params.id}` && to.hash !== ''))) {
      next({ path: to.path, hash: `#${this.$route.params.id}` })
    } else {
      next()
    }
  }

I hope it can help someone else.