I'm using React with Firebase to fetch data from firestore and display it to the user. Within a useEffect hook, I fetch the data and add it to an array of json objects. However, when adding a new element to the array, the previous one gets deleted. Below will be relevant portions of code.
const [items, setItems] = useState([]);
const [isLoading, setLoading] = useState(true);
const { currentUser } = useAuth();
function addItemToList(i) {
const updatedList = [
...items,
{
data: i.data(),
ref: i.ref
}
]
return updatedList;
}
useEffect(() => {
firestore.collection('items').where('uid', '==', currentUser.uid).get().then((itemSnapshot) => {
itemSnapshot.forEach((doc) => {
setItems(addItemToList(doc));
})
})
setLoading(false);
}, []);
I've also tried updating the items
list within the useEffect
hook, but it produces the same bug.