Home > other >  Write fetched data to variable from firebase realtime database react
Write fetched data to variable from firebase realtime database react

Time:03-31

enter image description hereI'm trying to save fetched data into variable, but I always get "too many rerenders" or "undefined". What I'm doing wrong

import {
  child,
  get,
  getDatabase,
  ref,
} from "firebase/database";

const db = getDatabase();

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetch = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        setData(fetched);
      });
      setTimeout(() => {
        console.log(data);
      }, 500);
    };
    fetch();
  }, []);
}

CodePudding user response:

There's no need of setTimeout(). You can print the data when the promise is resolved as shown below:

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetchData = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        console.log(fetched)
        setData(fetched);
      }); 
    };
    fetchData();
  }, []);
}

Also I've renamed the fetch function to avoid any confusion with Fetch API

  • Related