javascriptreactjsjoinnext.jstypeerror

TypeError: Cannot read properties of undefined (reading 'join')


TypeError

import { useRouter } from "next/router";

export default function PostAll() {
  const router = useRouter();
  const { all } = router.query;

  return (
    <div>
      <h1>Post: {all.join("/")}</h1>
    </div>
  );
}
wait  - compiling...
event - compiled client and server successfully in 32 ms (176 modules)
error - pages/post/[...all].js (9:21) @ PostAll
TypeError: Cannot read properties of undefined (reading 'join')
   7 |   return (
   8 |     <div>
>  9 |       <h1>Post: {all.join("/")}</h1>
     |                     ^
  10 |     </div>
  11 |   );
  12 | }
{
  "dependencies": {
    "next": "12.0.7",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
}

I am a very beginner and I am learning by watching online lectures. I can't quite figure out why I'm getting an error in this short code.


Solution

  • router.query by default is an empty object{}, so after const { all } = router.query;, all is undefined. And you can't call join on undefined, as the error is telling you. The real problem is OP is navigating to "localhost:3000/post/hello/world" but still getting a null pointer exception. The reason for that is the component pre-rendered with an empty object and then rendered again with the array. This behavior is in the documentation linked below. "It[query] will be an empty object during prerendering if the page doesn't have data fetching requirements." So what OP needs is just a null check.

    Documentation for the router is here

    return (
      <div>
        <h1>Post: {all && all.join("/")}</h1>
      </div>
    );