首页 > 解决方案 > NextJS - 你可以在有条件的情况下使用来自 api 的返回吗?

问题描述

我有一个更改密码功能,可以点击这个 api 进行验证,如果当前密码不正确,我想显示一个错误。

关于如何进行此操作的任何方向,或者如果我正在做的事情没有意义,请指出我正确的方向,如果会如此友好,将不胜感激!

case "PUT":
      try {
        const validContact = await Contact.findOne({ _id: req.body.id });

        const valid = bcrypt.compareSync(
          req.body.currentPassword,
          validContact.password
        );

        if (valid) {
          const hashedPassword = bcrypt.hashSync(
            req.body.newPassword,
            bcrypt.genSaltSync()
          );
          const contact = await Contact.findOneAndUpdate(
            { _id: req.body.id },
            { password: hashedPassword },
            { new: true }
          );

          res.status(200).json({ success: true, data: contact });
        }
        res.status(400).json({ success: false });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;

这是在提交表单时调用 API 的函数

const submitNewPassword = (submitNewPasswordForm, resetForm) => {
    submitNewPasswordForm(); // <-- I want to put this in a conditional
    resetForm();
    setOpenPasswordPopup(false);
    setNotify({
      isOpen: true,
      message: "Password updated successfully",
      type: "success",
    });
  };

编辑: submitNewPassword 功能

const submitNewPasswordForm = async () => {
    try {
      const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`, {
        method: "PUT",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });
      router.push(`${process.env.APP_DOMAIN}/`);
    } catch (error) {
      console.log(error);
    }
  };

标签: javascriptreactjsnext.js

解决方案


submitNewPasswordForm现在没有返回任何东西(嗯,它确实,但它只是一个空的 Promise)。为了能够检查它是否是一个好的请求,您需要从中返回一些东西。例子:

const submitNewPasswordForm = async () => {
  try {
    const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`, {
      method: "PUT",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(values),
    });

    // this check is also necessary; 400 isn't an exception that would get caught
    if (!res.ok) {
      throw new Error(res.statusText)
    }
    router.push(`${process.env.APP_DOMAIN}/`);
    return true;
  } catch (error) {
    console.log(error);
    // you could also re-throw the error, or return something else
    return false;
  }
};

因为它是一个异步函数,它返回一个 Promise,所以你需要用 a 来获取返回值.then

const submitNewPassword = (submitNewPasswordForm, resetForm) => {
  submitNewPasswordForm()
    .then((ok) => {
      if (!ok) {
        // show error
      } else {
        resetForm();
        setOpenPasswordPopup(false);
        setNotify({
          isOpen: true,
          message: "Password updated successfully",
          type: "success",
        });
      }
    })
};

如果你在第一个函数中重新抛出错误,你可以.catch这样做而不是检查一个ok值。如果您愿意,也可以将第二个函数async设为函数。例子:

const submitNewPassword = async (submitNewPasswordForm, resetForm) => {
  try {
    submitNewPasswordForm()
    // rest of the code
  } catch (err) {
    // show error
  }
}

无论您采用哪种方式,您都必须从函数中返回一些内容才能知道它是否成功。


推荐阅读