【问题标题】:Unable to capture data returned from API call in onSuccess callback无法在 onSuccess 回调中捕获 API 调用返回的数据
【发布时间】:2020-08-15 05:26:23
【问题描述】:

我正在使用 SWR react hook from nextJSonSuccess 回调函数,但它没有按我预期的那样工作。 onsuccess 回调被调用,但它没有收到任何数据。

这是显示问题的最少代码:

pages/index.js

import useSWR from "swr";

export default function index() {
  let data = { FirstName: "Default", LastName: "Default" },
    error;
  const fetcher = url =>
    fetch(url).then(r => {
      r.json();
    });
  const [shouldFetch, setShouldFetch] = React.useState(false);
  useSWR(shouldFetch ? "/api/data" : null, fetcher, {
    onSuccess: (data, key, config) => {
      console.log({ data }); //this always prints "undefined"
      this.data = data;
      this.error = error;
    }
  });

  function handleClick() {
    setShouldFetch(true);
  }
  return (
    <>
      <button onClick={e => handleClick()}>Fetch</button>
      Data retrieved from server is: {JSON.stringify(data)}
      Error received from server is: {JSON.stringify(error)}
    </>
  );
}

pages/api/data.js

export default (req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "application/json");
  res.send({ FirstName: "John", LastName: "Doe" });
};

当我转到 localhost:3000/index 并单击 Fetch 按钮时,它仍将 FirstName 和 LasName 显示为“默认”。

我认为我的onSuccess 回调函数有问题。

这里是codesanbdbox演示:https://codesandbox.io/s/nervous-hill-mn0kz?file=/pages/index.js

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    你需要做的是从fetcher function返回数据

    const fetcher = url =>
       fetch(url).then(r => {
       return r.json();
    });
    

    我还建议按照最佳实践重构代码。理想情况下,您应该将以下内容包装在一个函数中。

    useSWR(shouldFetch ? "/api/data" : null, fetcher, {
       onSuccess: (data, key, config) => {
          console.log({ data }); //this always prints "undefined"
          this.data = data;
          this.error = error;
       }
    });
    

    以防止每次响应渲染时都运行它。我还建议将数据移动到反应状态,而不是让 shouldFetch 处于状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多