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>
</>
);
}
>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]