eXception
eXception

Reputation: 2301

Wait until Pinia is loaded

Immediately launched code getting data from backend and tries to save them in Pinia. But got an error

getActivePinia was called with no active Pinia. Did you forget to install pinia?

Question: Can I create a function to check if Pinia already ready or not? Is that any flag I can check?

I expected to create a function like this, to check Pinia status in a given amount of time

function isPiniaReady() {
  let time = 0;
  const timeLimit = 300
  const interval = 30;

  return new Promise((resolve, reject) => {
    const index = setInterval(() => {

      // success
      if (....<pinia is ready>....) {  // <- how to write this condition?
        clearInterval(index);
        return resolve(true);
      }

      // fail
      if (time >= timeLimit) {
        clearInterval(index);
        return reject(new Error('Pinia is never ready'));
      }

      time += interval;
    }, interval)
  })
}

Upvotes: 0

Views: 3728

Answers (1)

Russ Deneychuk
Russ Deneychuk

Reputation: 815

You shouldn't be having that error if pinia is properly initiated with .use(pinia).

But in rare cases you might need to manual set active pinia with setActivePinia() method: https://pinia.vuejs.org/api/modules/pinia.html#setactivepinia

Not a great example, but an example: https://stackblitz.com/edit/vitejs-vite-52kkxc?file=src/components/DoubleCount.vue

Upvotes: 0

Related Questions