Search code examples
javascriptvue.jsvuex

Simulate delay in Vuex's action method


I am writing Vue application for backend which is still in development. For this reason I want add artificial delay to actions. For instance if I submit sign in, I want add delay 1 second and then redirect to main application.

this is submit method from component

onSubmit() {
  this.loading = true;
  this.$store.dispatch('auth/signIn', this.credentials).then(() => {
    this.loading = false;
  });
}

and here is action's signIn method:

  async signIn({ commit }, credentials) {
    const result = await authService.signIn(credentials);
    await commit(AUTHENTICATE, {
      authenticated: result
    });
  }

as you can see, I call there authService in which method I created timeout block which not work and service returns undefined

  async signIn(credentials) {
    setTimeout(() => {
      console.log('credentials', credentials);
      return true;
    }, 2000);
  }

Can you help me to fix it?


Solution

  • You don't return anything from your signIn method and setTimeout doesn't block code execution.

    If you want to make a blocking timeout, I suggest creating a delay() method, like this:

    function delay(time = 2500) {
      return new Promise((resolve) => {
        setTimeout(resolve, time)
      })
    }
    

    By default it will wait for 2.5 seconds.

    You can see a working example in vanilla JS here