[Vuejs]-How to fetch data before fetching other data Vue 3

0👍

You can use JS Promise, I don’t know how is built your useAuth and useHomePosts, but if it launches a fetch you can just return a Promise. It will look after that like this:

useAuth().then(
    (response) => {
        // You can make what you want here it's when the fetch is over example
        if (response.userData.value.following) {
            return getPosts(response.userData.value.following) //will return post with your userDataFollowing
        }
})

If you can add to your post your useAuth() and useHomePosts(). (without sensible data) I’ll maybe be able to help you more.

Javascript promise (Chained)

Hope it helps you ! 🙂

EDIT

I don’t know where your useAuth come from but I will use findUser for my example, you need to return a promise so for that you can modify your function like that :

async function findUser(email) {
  try {
    const queryData = query(dbUsersRef, where('email', '==', email));
    const unsubscribe = onSnapshot(queryData, (docs) => {
      docs.forEach((doc) => {
        const user = {
          id: doc.id,
          ...doc.data(),
        };

        userData.value = user;
      });
    });

    return new Promise((resolve, reject) => {
      unsubscribeFromUser.value = unsubscribe;
      resolve(queryData); // The treatment is over
    });
  } catch (e) {
    console.error(e);
    throw e;
  }
}

And then you can use it like that:

findUser('exemple@email.com')
  .then((user) => {
    if (user) {
      console.log(user);
      // you can get your posts here or whatever it is it will be launch when user is found
    } else {
      console.log('Nothing found');
    }
  })
  .catch((error) => {
    console.error(error);
  });

Still hope it helps you 🙂

Leave a comment