Next.js Discord

Discord Forum

throw from server actions

Unanswered
ABUL KALAM posted this in #help-forum
Open in Discord
I am writing a sever action to perform some operation on firebase. The issue is, when the operation is successful, the message against return is returned to client and displayed on the browser console. When there is an error, the message against throw is not returned to client, instead it is displayed on VS Code console.

Here is my file with server action:
"use server";
// imports

const deleteCityFromDB = async (id) => {
  try {
    const cityRef = doc(db, "City", id);
    const docSnapshot = await getDoc(cityRef);

    if (docSnapshot.exists()) {
      let usage = docSnapshot.data().usage;
      let usageCases = "";
      for (const key in usage) {
        if (usage[key] !== 0) {
          usageCases += key.toUpperCase() + ", ";
        }
      }
      if (usageCases !== "") {
        throw `City cannot be deleted. It is being used in ${usageCases.slice(0, -2)}.`;
      } else {
        await deleteDoc(cityRef);
        revalidatePath("/admin/roles-analytics-cities", "page");
        return "City deleted successfully!";
      }
    } else {
      throw "City deletion failed. Please try again later.";
    }
  } catch (error) {
    console.log("Error deleting the city: ", error);
    throw "City deletion failed. Please try again later.";
  }
};

export default deleteCityFromDB;


Here is my function in another file where I am calling the server action:
const deleteCityService = (
  itemToDelete,
  setShowModalSpinner,
  showAlert,
  hideModal
) => {
  setShowModalSpinner(true);
  deleteCityFromDB(itemToDelete.id)
    .then((response) => {
      console.log("then", response);
    })
    .catch((response) => {
      console.log("catch", response);
    })
    .finally(() => {
      hideModal();
      setShowModalSpinner(false);
    });
};

0 Replies