Marnie Rodriguez
Marnie Rodriguez

Reputation: 441

My function is being called before the state is changed

I'm working in Reactjs and my database is Firebase.

I'm trying to retrieve data from my database and then checking data regarding it.

At the top, I have const [group, setGroup] = useState(null); for my group data. In my CheckGroupRelationship function, if checks the database using the group object data.

Initially I had the function called after the database call:

  const GetGroupInfo = async (uid) => {
    await props.firestore
      .collection("groups")
      .doc(uid)
      .get()
      .then(async (doc) => {
        if (!doc.exists) {
          console.log("No such document!");
        } else {
          setGroup({
            id: doc.data().id,
            ownerID: doc.data().ownerID,
            name: doc.data().name,
          });
        }
      })
      .catch((err) => {
        console.log("Error getting document", err);
      });
      CheckGroupRelationship();
  };

However, I would get the error "Group is null". So I moved the function called to the setState:

  const GetGroupInfo = async (id) => {
    await props.firestore
      .collection("groups")
      .doc(id)
      .get()
      .then(async (doc) => {
        if (!doc.exists) {
          console.log("No such document!");
        } else {
          setGroup(
            {
              id: doc.data().id,
              ownerID: doc.data().ownerID,
              name: doc.data().name,
              bio: doc.data().bio,
            },
            CheckGroupRelationship()
          );
        }
      })
      .catch((err) => {
        console.log("Error getting document", err);
      });
  };

This would still result in the "group is null" error. I'm not sure what else I can do to get the function to be called AFTER the state is set.

Upvotes: 3

Views: 42

Answers (1)

Evgeny Klimenchenko
Evgeny Klimenchenko

Reputation: 1194

the easy solution would be to use useEffect. In your case you can do this:

const [group, setGroup] = useState(null);
useEffect(() => {
  if (group) {
    CheckGroupRelationship()
  }
}, [group])

What useEffect does here is waiting for group to change and when it changes it calls the inside callback. In this case you will have group updated there. Hope it helps, cheers

Upvotes: 1

Related Questions