Firebase: UseEffect onSnapShot returns empty array and then full array

Viewed 39

I am using:

const useItemsF = () => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const user = firebase.auth().currentUser;
  useEffect(() => {
    const unsubscribe = firebase
      .firestore()
      .collection("user")
      .where("id", "==", `${user.uid}`)
      .onSnapshot(snapshot => {
        const listItemsUsers = snapshot.docs.map(doc => ({
          ProfilePic: doc.get("userProfilePic")
        }));
        setItems(listItemsUsers);        
      });
    return () => unsubscribe();
  }, []);
  return items;
};

By why is it when loading the page that the console for the array returns empty multiple times before showing the full items array?

Is there a way to preload this before it renders the page? Or am I doing something wrong here?

1 Answers

Add a loading indicator to wait until the request back with data

const useItemsF = () => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const user = firebase.auth().currentUser;
  useEffect(() => {
    setLoading(true)
    const unsubscribe = firebase
      .firestore()
      .collection("user")
      .where("id", "==", `${user.uid}`)
      .onSnapshot(snapshot => {
        const listItemsUsers = snapshot.docs.map(doc => ({
          ProfilePic: doc.get("userProfilePic")
        }));

        setItems(listItemsUsers); 
        // data fetched 
        setLoading(false)
      });
    return () => unsubscribe();
  }, []);
  return items;
};

Related