Next.js Discord

Discord Forum

useSWR is not a function

Unanswered
European sprat posted this in #help-forum
Open in Discord
Avatar
European spratOP
I am attempting to use useSWR
package:
"next": "^13.4.6",
"swr": "^2.2.0",


It's a very basic fetch to get comments. My page shows this error:
- error src/app/(blog)/blog/[slug]/page.tsx (111:13) @ Page
- error TypeError: (0 , swr__WEBPACK_IMPORTED_MODULE_1__.default) is not a function
    at Page (blog/[slug]/page.tsx:105:97)


Page:

import useSWR from "swr";

export const revalidate = 6000;

const fetcher = async (url: string) => {
  const res = await fetch(url);

  if (!res.ok) {
    throw new Error("Error fetching data");
  }

  return res.json();
};

type Props = {
  params: {
    slug: string;
  };
};

const Page = async ({ params: { slug } }: Props) => {

  const {
    data: comments,
    error,
    isLoading,
  } = useSWR(`/blog/comments?slug=${slug}`, fetcher);


  return (
    <article>
      {isLoading ? (
        <p>
          Loading comments...
        </p>
      ) : (
        <ul>
          {comments?.map((comment) => {
            return (
              <li key={comment.id}>
                <span className="pr-2 font-serif font-bold">
                  {comment.user.name}:
                </span>
                <span>{comment.content}</span>
              </li>
            );
          })}
        </ul>
      )}
    </article>
  );
};

export default Page;

4 Replies

Avatar
joulev
You cannot use hooks (like useSWR) in server components
You have to make it a client component
Avatar
European spratOP
initiate walk-of-shame.exe
I should have known better. thanks 🙂