如何发出两个axios请求并将两个响应都保存在一个钩子中?

时间:2019-11-03 23:16:51

标签: javascript reactjs axios

我正在使用Axios对后端进行API调用。问题是,我要拨打电话,然后将响应保存在一个挂钩中,而不是拨打另一个电话,然后将响应保存在相同的挂钩中。我必须在收到第一个调用的响应后再进行第二个调用,因为在我的后端,第二个调用监听EventEmmiter:

const [invoice, setInvoice] = useState({
    loading: false,
    error: false,
    content: null,
    paid: false
  });

function createInvoice() {
    setInvoice({ ...invoice, loading: true });
    api
      .post("/lightning/createinvoice", {
        amount: values.amount
      })
      .then(response => {
        setInvoice({
          loading: false,
          error: false,
          content: response.data,
          paid: false
        });
        return api.get("/lightning/invoicestatus", {
          params: { id: response.data.id }
        });
      })
      .then(response => {
        if (response.data.status === "Confirmed")
          setInvoice({ ...invoice, paid: true });
      })
      .catch(() => {
        setInvoice({ loading: false, error: true, content: null });
      });
  }

此代码有效,但是我得到了invoices.content: null。我怀疑setInvoice({ ...invoice, paid: true });失败了,因为invoice状态没有最新状态。

我应该如何解决?

预先感谢

1 个答案:

答案 0 :(得分:1)

我已经做出了一种更简洁,更易读的方法,而不仅仅是承诺回调。如果您发现任何问题,请告诉我,因为我不确定我可以测试的实际API调用。但是下面的代码应该分别起作用。

  const [invoice, setInvoice] = useState({
    loading: false,
    error: false,
    content: null,
    paid: false
  });

  const createInvoice = async (api, values) => {
    try {
      setInvoice({ ...invoice, loading: true });
      const firstResponse = await api.post("/lightning/createinvoice", {
        amount: values.amount
      });
      setInvoice({
        ...invoice,
        content: firstResponse.data
      });

      const secondResponse = await api.get("/lightning/invoicestatus", {
        params: { id: firstResponse.data.id }
      });

      if (secondResponse.data.status === "Confirmed") {
        setInvoice({ ...invoice, paid: true });
      }
    } catch (err) {
      setInvoice({ loading: false, error: true, content: null });
    }
  };