GloatingCoder
GloatingCoder

Reputation: 1223

useEffect is exited before data is fetched and returns a few seconds of empty screen in react native

I have a use effect hook for fetching data on the home screen. I have set loading to true when execution begins and set it to false when the code is executed. I have a if else condition when the loading state is true, return a loading indicator otherwise if employee number is 0 then return an empty image else show the results. but when my home screen loads with data, there is a few seconds of empty image before the results are rendered. How do I show a loading indicator until all the data is fetched from firestore?

useEffect(() => {
    setLoading(true);
    employeeRef
      .where("userId", "==", currentUser.uid)
      .onSnapshot((snapshot) => {
        const newEmployee = [];
        snapshot.forEach((doc) => {
          newEmployee.push({
            id: doc.id,
            ...doc.data(),
          });
        });
        setEmployee(newEmployee);
      });
    setLoading(false);
  }, []);

Upvotes: 0

Views: 38

Answers (1)

Teodor
Teodor

Reputation: 416

I would suggest to

  1. set the default value of loading to true when you define the state: const [loading, setLoading] = useState(true);

  2. move the setLoading(false) call right after setEmployee(newEmployee) - to be called when the data arrives and is processed

Upvotes: 1

Related Questions