1

I'm using Next.js and React-query to implement a useUser Hook for page processing through user authentication.

I have implemented useUser Hook normally and it runs fine in develop.

However, when building through npm run build, the following error occurs and an error occurs in the build.

Error occurred prerendering page "/login". Read more: https://nextjs.org/docs/messages/prerender-error Error: No QueryClient set, use QueryClientProvider to set one at Object.useQueryClient

I guess react-query throws an error, but I don't know how to fix it.

how do i solve it??

///useUser.tsx
const useUser = ({ redirectTo, redirectIfFound }: IParams) => {
  const { data, error } = useQuery(["authed"], isAuthed);
  const [calledPush, setCalledPush] = useState(false);

  const user = data?.data;  //Returns true if the user is authenticated, false otherwise
  const hasUser = user;

  useEffect(() => {
    if (!redirectTo) return;
    if ((redirectTo && !redirectIfFound && !hasUser) || (redirectIfFound && hasUser)) {
      let calledPushLatest;
      setCalledPush((latest) => {
        calledPushLatest = latest;
        return latest;
      });

      if (calledPushLatest) return; // router.push has already been called

      // proceed to redirect
      setCalledPush(true);
      Router.push(redirectTo);
    }
  }, [redirectTo, redirectIfFound, hasUser]);

  return error ? null : user;
};
//index.tsx
const Home: NextPage = () => {
  const router = useRouter();
  // const user = useUser({ redirectTo: "/login" });

  // if (user === undefined || user === false) {
  //   return <div>Loading...</div>;
  // }

 //^ If I uncomment this part, the above error occurs.
  return (
    <div>
      <Head>
        <title>Our-Survey</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div>Home</div>
    </div>
  );
};

This is my package.json dependency.

  "dependencies": {
    "@tanstack/react-query": "^4.0.10",
    "@types/recoil": "^0.0.9",
    "axios": "^0.27.2",
    "js-cookie": "^3.0.1",
    "next": "12.2.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-icons": "^4.4.0",
    "react-query": "^3.39.1",
    "recoil": "^0.7.4"
  },
  "devDependencies": {
    "@types/js-cookie": "^3.0.2",
    "@types/node": "18.0.6",
    "@types/react": "18.0.15",
    "@types/react-query": "^1.2.9",
    "babel-jest": "^28.1.3",
    "typescript": "4.7.4"
  }

How do I solve it to make it build normally?

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.