Next.js Discord

Discord Forum

TypeError: Cannot read properties of null (reading 'useContext')

Unanswered
dante posted this in #help-forum
Open in Discord
import { useEffect } from "react";
import { useRouter } from "next/router";
import axios from "axios";
import { useCookies } from "react-cookie";
import {
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URI,
  API_BASE_URL,
} from "../../../config";

const Callback = () => {
  const router = useRouter();
  const [cookies, setCookie] = useCookies(["access_token"]);

  useEffect(() => {
    const fetchAccessToken = async () => {
      try {
        const code = router.query.code;

        if (code) {
          const response = await axios.post(`${API_BASE_URL}/oauth2/token`, {
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET,
            grant_type: "authorization_code",
            code,
            redirect_uri: REDIRECT_URI,
            scope: "identify",
          });

          const { access_token } = response.data;

          // Save the access token in cookies
          setCookie("access_token", access_token, { path: "/" });

          // Redirect back to the original window
          window.opener.postMessage(
            { code: access_token },
            window.location.origin
          );
          window.close();
        }
      } catch (error) {
        console.error(error);
      }
    };

    fetchAccessToken();
  }, [router.query.code, setCookie]);

  return null;
};

export default Callback;

1 Reply

(line 13): const router = useRouter();

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
 ⨯ TypeError: Cannot read properties of null (reading 'useContext')