Search code examples
javascriptreactjsnext.js

next.js dynamic route || TypeError: Cannot destructure property 'id' of 'router.query' as it is undefined


I create in next.js dynamic page by id.

Structure: app/shop/[id]/page.tsx

content:

"use client"

....
import { useEffect, useState } from 'react';
..
..
import { useRouter } from 'next/navigation';


    export default function Shop({ children, sections = [] }) {
      const [shopData, setShopData] = useState(null);
      const router = useRouter();
    
      // Get the id from the route
      const { id } = router.query;
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            if (id) {
              const response = await fetch(`/api/shop/${id}`);
        
              if (response.ok) {
                const result = await response.json();
                setShopData(result.shop);
              } else {
                console.error('Failed to fetch shop:', response.statusText);
              }
            }
          } catch (error) {
            console.error('Error fetching shop:', error);
          }
        };
    
        fetchData();
      }, [id]);

I try pass page ID to API but everytime I get

Unhandled Runtime Error
TypeError: Cannot destructure property 'id' of 'router.query' as it is undefined.

Source
app\shop\[id]\page.tsx (25:10) @ id

  23 | 
  24 | // Get the id from the route
> 25 | const { id } = router.query;

also I try router.query.id fallowing to documentation next.js but also the same issue.

Also I try change from import { useRouter } from 'next/navigation'; to import { useRouter } from 'next/route'; but then I get useRouter is not mounted.


Solution

  • if you are using page router try this:
    import { useRouter } from "next/router";

    or if you are using app router then you can use :

    import { usePathname } from 'next/navigation';

    in the component function const pathname = usePathname();

    pathname is what you want

    check this for more info Next.js UseRouter not mounted