1
votes

I am working with vuejs and vue-router in Rails app. I have a button which calls a nivagate method. When user clicks on this navigate method, it hits an API enpoint via axios module and move to next component using this.$router.push({name: "RouteName"}). Problem is, when user clicks multiple on this button it gives Uncaught (in promise) undefined error in console. My guess is this error occurs because of vue-router. My question is, how can I catch or handle this error. I am using multiple such buttons in my app so I need a generic solution.

Home.vue - component

<template>
  <div>
    <button
      id="select_button"
      @click="onSelectClick"
    >
     Select
    </button>
  </div>
</template>
<script>
  export default {
    onSelectClick() {
      this.$`enter code here`axios.get('some-url').then(res => { 
        //print res on console
      }).catch(err => { 
        // print err on console
      })
      this.$router.push({ name: 'route-name' }); //route-name != home
    }
  }
</script>
<style>
</style>

Error I get when I double(or more)-click on button

Uncaught (in promise) undefined
2
Welcome to stack overflow! Unfortunately, this question is not detailed enough to give you any meaningful help. Please edit your question to include a minimal reproducible example for the issue, including sample input, preferred output, and code for what you've tried so far. Also, since you have an error, please include the full error traceback in the text of the question.E. Zeytinci
@E.Zeytinci thank you for guidance. I have added simplified form of the code which is causing the issue. Hope it will help.H M Kashif Ali
if this is vue CLI, I might suggest this: alligator.io/vuejs/lodash-throttle-debounceMayra Navarro
@MayraNavarro this is not a vue CLI. I am integrating vue in Rails app.H M Kashif Ali
Perhaps you should only navigate to the next route if/when the API replies with no error ?IVO GELOV

2 Answers

1
votes

Error Cause: vue-router causes this error when we call this.$router.push({name: 'route-name'}) back to back multiple times without completing the previous call.

Solution: I can handle this error by adding a catch guard on router.push.

this.$router.push({name: 'router-name'}).catch(error => { //handle error here})

I made it generic by adding a method in vue mixin.

import router from '../router'
Vue.mixin({
  methods: {
    navigate(route) {
      router.push(route).catch(err => { //handle error here });
    }
  }
});

Now I can use this navigate method in my components like this.

<template>
</template>
<script>
  export default {
    mounted() {
      this.navigate({name: 'Home'})
    }
  }
</script>
<style>
</style>

Hope it helps others.

0
votes

next({name: 'Login'})

causes Uncaught (in promise)...

I replaced it with

router.push({name: 'Login'})
return

and no error!