Search code examples
javascriptroutesnext.jsnext-router

Using Next.JS Router Error: Cannot read properties of null (reading 'useContext')


First of all, I'm kinda new to Next.js, and React in general.

I have the page "Projects" and I want to redirect the user to the Product Page Details and I'm using this:

const openProjectDetails = () => {
  Router.push('/api/' + props.projetos.key);
}

And this is the code in the "/api/[key].js"

import { useRouter } from 'next/router';

const ProjectDetails = () => {
   const router = useRouter();
   const { key } = router.query;
   
   return (
      <div>
         {/* Display the project details */}
      </div>
   );
};

export default ProjectDetails;

What I'm I missing? This is the only page that gives me that error, and the error comes from: const router = useRouter();

Sorry again if this is basic, but I'm new to this.

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

I'm expecting to pass the key value and get all project fields from db, but because of that error, it doesnt work.


Solution

  • You cannot use useRouter in an API page since it is a hook and can only be used in client side pages (while API pages are server side).

    It doesn't seem like you understand the whole idea of API pages since they shouldn't return an HTML element but JSON and etc, this is why I would recommend to just use /projects/[key].js instead of API if you wish to have an HTML page and not a JSON file.

    But regardless, if you want to get the value of [key] you don't even need useRouter. Your ProjectDetails function should look like this:

    const ProjectDetails = ({params}) => {
       
       const key = params.id
       // key now has the value of [key] in the URL
       
       return (
          <div>
             {/* Display the project details */}
          </div>
       );
    };