0

I'm, a bit new to vue so please be kind. I have a simple push call I want to run 2 seconds after a user uploads a photo to my app. I'm trying to do this inside my axios "then" but it happens instantly. I want to make this take place after 2 seconds. How can I use setTimeout to accomplish this?

I've seen the answer here...How to add delay to promise inside then

But my mind is melting trying to understand it.

```

  axios.put(`${process.env.KITTY_URL}/api/v1/cats/${this.singleCat.id}/`,formData,{
          onUploadProgress: progressEvent => {
            console.log('Upload progress: ' + Math.round(progressEvent.loaded / progressEvent.total * 100) + '%')
          }
        })
          .then(response => {
            response.status === 200 ? this.showSuccess = true : this.showDanger = true;
            this.singleCat = response.data;
            // NOTE: set a timer to run this line 2 seconds after success response
            setTimeout(function() { this.$router.push('/login'); }, 2000)<---WHAT SHOULD THIS LOOK LIKE?
          })
          .catch(error => {
            console.log(error);
            this.showDanger = true;
          })

```

Jessi
  • 791
  • 1
  • 12
  • 24

1 Answers1

0

First off, you need to bind the context. Easiest way to do this is just with an arrow function. So you would just need to change that line to this:

setTimeout( () => this.$router.push('/login'), 2000);

Another way is to use async/await:

let response = await axios.put(...);
setTimeout( () => this.$router.push('/login'), 2000);

Though you won't have as nice of error handling this way: https://github.com/axios/axios/issues/1086

Similar question: Accessing VUE JS's data from Axios

Xander Luciano
  • 3,753
  • 7
  • 32
  • 53