Search code examples
javascriptvue.jses6-promisevuex

Vuex dispatch doesn't return


I have this code:

signin(context, payload, resolve) {
    console.log("SIGNIN action")

    const aemail = payload.locmail
    const apassw = payload.locpass

    backend.get("api/auth/signin", {
      headers: {
        'planck': 'FRESH'
      },
      crossDomain: true,
      params: {
        password: apassw,
        email: aemail
      }
    }).then(function(ret) {
      console.log("SENT")
      if (ret.data.auth === 'TRUE') {
        context.commit('authenticate', ret.data.planck)
        state.isAuthenticated = true
      } else {
        state.isAuthenticated = false
      }
      console.log(ret)
      return Promise.resolve(ret)
    });
  }

and when I call it from component:

this.$store.dispatch('signin', {
        locmail,
        locpass
      }).then(ret => {
        console.log(ret);
      });

then console log prints undefined. What am I doing wrong here? In documentation I read that I should use resolve() but then I get error that it's not a function.


Solution

  • Return the backend promise in the signin action.

      signin(context, payload) {
        // ...
    
        // The action needs to return a Promise
        return backend.get("api/auth/signin", {
          /* ...*/
        }).then(function(ret) {
          /* ... */
        });
      }
    

    Also, it looks like you're changing a state object in the action and this should be limited to mutations.

    If you're using the strict mode in development, you'll see a warning about this.