Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

runTransaction firebase async await return undefined

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading