I am trying to fetch data from firebase but I get duplicate data on the app. I clear the state of orders before fetching and then combine all orders from different customers but the problem is that, I get prev. orders and prev. orders + new orders all combined. What I want prev. order + new order only.
useEffect(() => {
let customerList1 = [];
const unsubscribe = firebase
.database()
.ref(`/serviceProvider/${user1.uid}/franchise/customers`)
.orderByKey()
.on("value", (snapshot) => {
customerList1.push(snapshot?.val());
setCustomerList(customerList1);
// setCustomerList(snapshot.val());
});
setShowloading(false);
return unsubscribe;
}, [user1.uid]);
useEffect(() => {
const innerSubscriptions = [];
// let orderList1 = [];
if (customerList) {
setOrders([]); // <-- clear orders
Object.values(customerList).forEach((customer) => {
if (customer) {
Object.values(customer).forEach((id) => {
const unsubscribe = firebase
.database()
.ref(`/orders/${id}`)
.orderByKey()
.on("value", (snapshot, key) => {
// Grab all orders from the customers and merge
const order = snapshot?.val();
// setOrders([...orders, order]); // realtime but gets only last customerList orders
setOrders((orders) => [...orders, order]); // realtime all orders but reapeated the list and new orders
// setOrders((orders) => {
// return [...orders, order]
// });
setShowloading(false);
});
innerSubscriptions.push(unsubscribe);
});
}
});
}
return () => {
innerSubscriptions.forEach((unsubscribe) => unsubscribe);
};
}, [customerList]);