Home > Back-end >  How to stop useAsyncState from running immediately?
How to stop useAsyncState from running immediately?

Time:08-24

I am trying to use the useAsyncState() from the VueUse library.

I am using the { immediate: false } option flag because I do NOT want it to run immediately.

But the code always gets run immediately, and I don't know why.

Here is my code:

import { useAsyncState } from '@vueuse/core';
const firstNameSubmit = useAsyncState(
  new Promise((resolve) => {
    setTimeout(() => {
      console.log('Bob');
      resolve();
    }, 2000);
  }),
  undefined,
  { immediate: false }
);

const handleFirstNameSubmit = () => {
  firstNameSubmit.execute();
};

And here is a reproduction: https://stackblitz.com/edit/vitejs-vite-ylzoyt/?file=src/App.vue

I also tried doing the opposite and using { immediate: true }, along with excluding the options object altogether, but none of those solutions work.

The promise inside useAsyncState always runs immediately.

CodePudding user response:

Once a promise is created, it cannot be postponed. In order to avoid this, it should be wrapped with a function that can be explicitly called.

It should be:

const firstNameSubmit = useAsyncState(
  () => ...,
  undefined,
  { immediate: false }
);

...

firstNameSubmit.execute();
  • Related