I am trying to setEventsList state to have the eventList but I always get an infinite loop. I have successfully gotten the data from firebase as objects and I also want to change the object into an array so that the map function does not throw an error.
import React, { useEffect, useState } from 'react';
import { realDB } from '../../firebase/firebase'
import Card from '../events/events'
function CardList(props) {
const [eventsList, setEventsList] = useState([]);
useEffect(() => {
const eventsRef = realDB.ref('/Events').limitToFirst(5);
eventsRef.on('value', (snapshot) => {
var events = snapshot.val();
let eventList = []
for (let id in events) {
eventList.push({
EventName: events[id].EventName,
EventEntryFee: events[id].EventEntryFee,
Eventsport: events[id].Eventsport,
eventCurrentParticipants: events[id].eventCurrentParticipants,
EventMaximumParticipants: events[id].EventMaximumParticipants,
EventTotalPrizes: events[id].EventTotalPrizes,
EventDifficulty: events[id].EventDifficulty
});
}
setEventsList(eventList);
console.log(eventsList);
});
}, [])
return (
<div>
{eventsList
? eventsList.map((event, index) => (
<Card key={index} />
)) : (
<><p> No data</p></>
)}
</div>
);
}
export default CardList;
// contents of '../../firebase/firebase'
import firebase from "firebase";
import 'firebase/auth'
// Initialize Firebase
const app = firebase.initializeApp({
apiKey: "AIzaSyBxxxxx1wQA",
authDomain: "fantasxxxxxxxaxxpp.x",
databaseURL: "https:xxxxxe.x.com",
projectId: "fxxxxxe",
storageBucket: "fantxxxm",
messagingSenderId: "xxxx",
appId: "1:xxx",
measurementId: "Gxx-xxxxx"
});
// firebase.analytics();
const db = app.firestore()
const realDB = app.database()
const auth = app.auth()
export { db, auth, realDB }
eventsRefneed to unsubscribe from anything to remove the listener and end state updates?useEffecthook only runs once, so either manyonValueevents are occurring, or thisCardListcomponent is being repeatedly remounted so the effect is running each time. Do you know how often that event is emitted? You can easily test the remounting theory withuseEffect(() => console.log('MOUNTED'), []);and if you see a bunch then you know it's remounting.