I am working on an inventory project using React. Before pushing the data in progress.json I want to check if that data is already present in progress.json file to prevent duplication using the id provided to each dataset. As I am still learning React I am out of solutions for this problem.
export async function progressOrders (found){
const loadedOrders = await fetchOrders('progress');
let result;
//for(const key in loadedOrders){
// result = loadedOrders.filter(() => {
// return loadedOrders[key].id === found.id
// });
//};
loadedOrders.map(() => {
for(const key in loadedOrders){
if(loadedOrders[key].id === found.id){
return result = true;
}else{
return result = false;
}
}
return result;
});
console.log(result);
if(result === true){
alert('Order already in progress state');
}else{
const response = await fetch(`${FIREBASE_DOMAIN}/progressOrders.json`,{
method:"POST",
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify({
id: found.id,
dryFruit: found.dryFruit,
weight: found.weight,
canteenName: found.canteenName,
orderQuantity: found.orderQuantity,
newOrderTime: found.newOrderTime
})
});
if(!response){
throw Error('Order not in progress');
}else{
alert('Order is in progress now.');
};
}
};
If you want to prevent duplication, always use the thing that needs to be unique as the key for that data in the database.
Where you now store:
progressOrders: {
"somemeaninglesspushid": {
...
"id": "orderIdThatMustBeUnique"
}
}
Consider changing that to:
progressOrders: {
"orderIdThatMustBeUnique": {
...
}
}
With this data structure the order ID is by definition going to be unique inside of progressOrders, as keys are by definition unique with a JSON object.
This new data structure also ensures that there's no harm in writing the same order information multiple times. The result after the second (or any subsequent) write is the same as the result after the first write, a concept known as idempotency.