Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can someone tell me why this page constantly prints the console log output?

Update: i put the function inside a hook and used a constant variable to hold the data instead of useState.

When i come on this page, when i look at the console its a never ending list of the console output, why doesnt it just do it once ? i only called the function once.

import { auth } from "../../components/firebase";
import { database } from "../../components/firebase";
import { ref, child, get } from "firebase/database";
import { useState, useEffect } from "react";

export default function Dashboard() {
  const dbRef = ref(database);

  const getData = () => {
    get(child(dbRef, "users/"))
      .then((snapshot) => {
        const data = (snapshot.val());
        console.log(data);
      })

      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() =>{
    getData();
  }, []);

  return (
    <>
      <div>Properties</div>
    </>
  );
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s because the function gets called by react many times on every re-render. If there is something you want to run once, or when some data changes, use useEffect hook as follows

Put getData() in useEffects.

import { auth } from "../../components/firebase";
import { database } from "../../components/firebase";
import { ref, child, get } from "firebase/database";
import { useState, useEffect } from "react";

export default function Dashboard() {
  const dbRef = ref(database);
  const [userInfo, setUserInfo] = useState([]);

  const getData = () => {
    get(child(dbRef, "users/"))
      .then((snapshot) => {
        setUserInfo(snapshot.val());
        console.log(userInfo);
      })

      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(()=>{
    getData();
  }, [dbRef])

  return (
    <>
      <div>Properties</div>
    </>
  );
}

The following runs when the variables passed to useEffects changes [dbRef]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading