I am trying to set the data returned from firebase in useState
variable but I got maximum call stack size exceeded
error in console. However console.log(items, "items");
returns the actual data from firebase, Here is my code.
function Profile() {
const [items, setItems] = useState([]);
const { currentUser } = useAuthValue();
const starCountRef = ref(db, "doctors");
onValue(
starCountRef,
(snapshot) => {
const data = snapshot.val();
if (data !== null) {
setItems(data);
}
},
{
onlyOnce: true,
}
);
console.log(items, "items");
}
Is there a way to use closure in this case?
CodePudding user response:
You need to put your onValue
in a useEffect
, otherwise it gets called every time the component re-renders. Since it updates the state, it causes the component to re-render which is causing it loop infinitely.
useEffect(()=>{
onValue(
starCountRef,
(snapshot) => {
const data = snapshot.val();
if (data !== null) {
setItems(data);
}
},
{
onlyOnce: true,
})
},[])