Home > Net >  How do I structure a fetch request after an other?
How do I structure a fetch request after an other?

Time:12-28

I have a React blog and I am using Firebase as a back-end. I use createUserWithEmailAndPassword method and after authentication users are redirected to blog where they can start adding blogs.

I store their posts in a firestore collection "posts". No problem with that.

I also want a user object to be created after login with the user preferences. Let's say a specific theme each one has chosen.

I create a collection called "users" at firestore and where I will store each ones object {user: "[email protected], theme: "dark" ,isAdmin: false, etc} using addDoc method.

I want this object to be created once though and not every time a user logs in.

How do the check on that "users" collection if the user already exists?

I get the collection getDocs(userCollectionRef) and then I filter the data let's say by a property to see if there is that object there.

And if not I want to add the document using addDoc method.

this is the request:

useEffect(() => {
  const createUserData = async () => {
    const data = await getDocs(usersCollectionRef);
    const docs = data.docs.map((doc) => ({
      ...doc.data(),
      id: doc.id,
    }));
    const userData = docs.filter((doc) => doc.user === user.email);

    if (userData.length === 0) {
      await addDoc(usersCollectionRef, {
        user: user.email,
        isAdmin: false,
        theme: "dark",
      });
    }
  };
  if (user) {
    createUserData();
  }
}, [user, usersCollectionRef]);

It seems like I am trying to check and add to the collection at the same time and this is why it doesn't work.

Any ideas?

Should I have an in-between step where I store what I'm getting from the getDocs in a state or something and then do the second request?

Can anyone explain please?

CodePudding user response:

I changed the if statement to a return like so and it worked.

 return (
    userData.length === 0 &&
    (await addDoc(usersCollectionRef, {
      user: user.email,
      wordGoal: wordGoal,
    }))
  );

I guess I return the second promise after the first now that's why

CodePudding user response:

I guess when the getDocs request happens because its asynchronous the data then are empty then the code proceeds to the if statement which at that point is true (we have no records) and so executes it.

  • Related