【问题标题】:useSWR successfully fetches , but data returns undefineduseSWR 成功获取,但数据返回未定义
【发布时间】:2023-01-11 21:22:17
【问题描述】:

我正在使用 useSWR 挂钩从 API 获取和显示数据。

代码是:

const backendURL = process.env.NEXT_PUBLIC_BACKEND_URL;
  const { data: session, status } = useSession();
  let userToken = null;

  useEffect(() => {
    if (status == "authenticated") {
      console.log(status);
      userToken = session.user.accessToken;
      console.log(session.user.accessToken);
    }
  }, [session, status]);

  const fetcher = (url) => {
    axios
      .get(url, {
        headers: {
          Authorization: `Bearer ${session.user.accessToken}`,
          "Content-Type": "application/json",
        },
      })
      .then((res) => {
        return res;
      })
      .catch((err) => console.log(err));
  };

  const { data, error, isLoading, isValidating } = useSWR(
    `${backendURL}/content/get_all/content_type`,
    fetcher,
    { refreshInterval: 1000 }
  );

当我控制台在 .then() 中记录响应时,功能类似于

.then((res) => console.log(res))

它 console.logs 响应,并且在网络部分我可以看到数据已成功获取。

但是当我添加console.log(data)时,它总是未定义的。

我该如何解决这个问题?

我的依赖项:

"dependencies": {
    "@svgr/webpack": "^6.5.1",
    "antd": "^4.23.4",
    "axios": "^1.2.2",
    "cookies-next": "^2.1.1",
    "less": "^4.1.3",
    "next": "^12.2.5",
    "next-auth": "^4.18.8",
    "react": "^18.2.0",
    "react-calendar": "^4.0.0",
    "react-cookie": "^4.1.1",
    "react-dom": "^18.2.0",
    "swr": "^2.0.0"
  },
  "devDependencies": {
    "@types/node": "18.7.23",
    "@types/react": "18.0.21",
    "@types/react-dom": "18.0.6",
    "autoprefixer": "^10.4.12",
    "eslint": "8.24.0",
    "eslint-config-next": "^13.1.1",
    "postcss": "^8.4.17",
    "tailwindcss": "^3.2.4"
  }

【问题讨论】:

    标签: next.js axios fetch next-auth swr


    【解决方案1】:
    .then((res) => {
      console.log(res); // console.log returns undefined.
      return res;
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多