Whenever my page loads I execute the useEffect() function below to retrieve data from firebase and set it to my local state calendarList but every time the page renders it makes a duplicate of the data and pushes is to the state so I have twice as many objects stored. How can I prevent this from happening?
STATE
const [calendarList, setCalendarList] = useState([]);
USE EFFECT - executes on page load
useEffect(() => {
db.collection("users")
.doc(userId)
.collection("calendars")
.onSnapshot((snapshot) => {
const calendarArray = [];
snapshot.forEach((doc) => {
calendarArray.push(doc.data()); push all doc obejects to calendar array
});
setCalendarList(calendarArray); //set state
});
}, []);
you can create a custom hook, perhaps.
create a new file and call it as you wish, but gurus out there says it must have to start with use
//useCalendar.js
import {useState, useEffect} from "react";
const useCalendar = (userId) => {
const [calendarList, setCalendarList] = useState([]);
const addItem = (item) => {
// use this to add mow items
};
const cleanList = () => {
setCalendarList([]);
}
const getItemById = (id) => {
// use this to get an item
};
useEffect(()=> {
db.collection("users")
.doc(userId)
.collection("calendars")
.onSnapshot(snapshot => {
const calendarArray = snapshot && snapshot.map(doc => doc.data());
setCalendarList(calendarArray || []);
});
},[userId, list]);
return {
calendarList,
addItem,
cleanList,
getItemById
};
}
export default useCalendar;
now at yow component use it like
const component = () => {
const { calendarList, addItem, cleanList, getItemById } = useCalendar(userId);
...
}