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>
</>
);
}
CodePudding user response:
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]
CodePudding user response:
If the function is called without ending, it means the component is render constantly. The component is render if the parent component renders or if the props change. Check the render of the parent component using a console.log("...")