Search code examples
next.jsaxiosfetchnext-authswr

useSWR successfully fetches , but data returns undefined


I am using useSWR hook to fetch and display a data from an API.

the code is :

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 }
  );

when i console log the response in .then() function like

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

it console.logs the response, and in also network section I can see that data is fetched succesfully.

but when i add console.log(data) it is always undefined.

How can i solve this?

my dependencies:

"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"
  }

Solution

  • try to return the axios in the fetcher callback

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

    or remove the curly braces

    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));