with FirebaseFirestoreService I wrote this function to get and update at collection "setting"
export const handleGetOrderId = async () => {
const settingDocRef = doc(db, "restaurant", "9NmmWP99jNciAqVqLROy", "setting", "9NmmWP99jNciAqVqLROy");
try {
await runTransaction(db, async (transaction) => {
const sfDoc = await transaction.get(settingDocRef);
if (sfDoc.exists()) {
transaction.update(settingDocRef, { orderId: increment(1) });
if (sfDoc?.data().orderId) {
const new_id = parseFloat(sfDoc?.data().orderId) 1;
return String(new_id).padStart(6, "0");
} else {
return "000001";
}
}
});
} catch (e) {
console.error(e);
}
};
At frontend side I invoke "handleGetOrderId" like this
const orderId: any = await handleGetOrderId();
But it return "undefined" and I want to see a type of string just like auto-generated-ID of firebase - I was tried so many way to resolve but nothing changed. Someone please tell me where I wrong.
CodePudding user response:
You are not returning anything from handleGetOrderId()
function. The resolved promise of runTransaction
is the data returned from transaction. Try refactoring the code as shown below:
export const handleGetOrderId = async () => {
const settingDocRef = doc(db, "restaurant", "9NmmWP99jNciAqVqLROy", "setting", "9NmmWP99jNciAqVqLROy");
try {
const trasactionResult = await runTransaction(db, async (transaction) => {
const sfDoc = await transaction.get(settingDocRef);
if (sfDoc.exists()) {
transaction.update(settingDocRef, {
orderId: increment(1)
});
if (sfDoc?.data().orderId) {
const new_id = parseFloat(sfDoc?.data().orderId) 1;
return String(new_id).padStart(6, "0");
} else {
return "000001";
}
}
});
// Add return here
return transactionResult
} catch (e) {
console.error(e);
}
};
Checkout passing information out of transaction part in the documentation.