0

I'm trying to read the data from firebase real-time database. When I console log the snapshot, I can see that in the array that I push. But when I try to assing that to state it either returns undefined or sometimes only "No data available.". I'm pretty new to firebase so I'm really sorry if it is bad question.

  //show user's liked image on the UI
     export const useShowLikedImageFromDB = () => {
      const [data, setData] = useState([]);
    
      const currentUser = useAuth();
      useEffect(() => {
        let results = [];
        const dbRef = ref(getDatabase());
    
        return get(child(dbRef, "users/" + currentUser?.uid + "/likes"))
          .then((snapshot) => {
            if (snapshot.exists()) {
              snapshot.forEach((item) => {
                results.push(item.val());
                setData((prev) => [...prev, results]);
              });
    
              console.log(data);
            } else {
              console.log("No data available");
            }
          })
        .catch((error) => {
          console.error(error);
          });
      }, []);
    
      return { data };
    };
etrafa
  • 1
  • 1
  • Setting the state on a component is, just like loading data from Firestore, an asynchronous operation, and is not completed by the time your `console.log(data);` runs. You should either log `results` inside this code, or use another `useEffect` to respond to the state of `data` being updated. – Frank van Puffelen Jun 28 '22 at 14:29
  • Hello, thanks for the response. But when I use data as an useEffect dependecy, I'm getting infinitive loop. – etrafa Jun 29 '22 at 09:25
  • It should be a separate `useEffect`, as yuo can't have a circular dependency. – Frank van Puffelen Jun 29 '22 at 16:47

0 Answers0