Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Vuex - Promise that resolves on state change?

Is it possible to create a Promise that resolves once a variable in the global vuex store changes?

I have a variable that is initialized as null in the state store and will be populated via an asynchronous call.
A different part of the app is dependent on that variable being true or false and is supposed to wait while it is still null.

Is there a way to cleanly wait for the change of this variable?

like image 796
TommyF Avatar asked Oct 06 '18 14:10

TommyF


2 Answers

You can vm.$watch on an expression or function and then wrap that with a promise.

function watch(vm, fn) {
  return new Promise(resolve => {
    const watcher = vm.$watch(fn, (newVal) => {
      resolve(newVal);
      watcher(); // cleanup;
    });
  });
}

This would let you do something like:

let change = await watch(vm, () => state.foo); // will resolve when state.foo changes

Inside an async function.

Note in general this isn't a terrific pattern and in most cases it is preferable and simpler to use a computed property (and not a promise) for this.

like image 52
Benjamin Gruenbaum Avatar answered Sep 17 '22 12:09

Benjamin Gruenbaum


Similar to Benjamin's answer and not exactly what you are asking for, just another option. Instead of watching state change you can subscribe to when a mutation of a specific type occurs and wrap that into a Promise.

new Promise(resolve => {
      let unsubscribeFn = this.$store.subscribe(mutation => {
        if (mutation.type === "MY_MUTATION") {
          unsubscribeFn();
          resolve();
        }
      });
    });
like image 32
Kflexior Avatar answered Sep 21 '22 12:09

Kflexior