How can I ensure that the Next.js router.query is not undefined?

Viewed 4934

I'm using next.js and the import { useRouter } from 'next/router'.

However on initial load, router.query.id is undefined. It quickly fills in, but that initial load is a killer.

I'm trying to figure out how to do it, and tried:

export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  // const res = await fetch(`https://.../posts/${params.id}`)
  // const post = await res.json()
  console.log(params)
  // Pass post data to the page via props
  return { props: { params } }
}

but this returns an error:

Error: getStaticPaths is required for dynamic SSG pages and is missing for '/app/d/[id]'.

I can't use getStaticPaths, since [id] is variable and can be any number of things.

So what's the best way to handle this?

1 Answers

I would do smt like this(without staticProps):

function Page(props) {
  const router = useRouter();
  const { query = {} } = router || {};
  const { id = 0 } = query || {};
  
  useEffect(()=> {
    if(id) {
      (async ()=> {
        const res = await fetch(`https://.../posts/${id}`)
        const post = await res.json();
      })();
    }
  }, [id]);

}

And this is what official doc. says:

// You also have to define a Post component in the same file (pages/posts/[id].js)
function Post({ post }) {
  const router = useRouter()

  // If the page is not yet generated, this will be displayed
  // initially until getStaticProps() finishes running
  if (router.isFallback) {
    return <div>Loading...</div>
  }

  return <h1>Posts are here</h1>;
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return { props: { post } }
}

UPDATE:

After a bit research, have figure out this solution with staticProps:

export default function Post({ post }) {
  return <h1>Post is here</h1>;
}


export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: '*' } }
    ],
    fallback: true
  };
}
    
export async function getStaticProps(context) {

  const res = await fetch(`https://api.icndb.com/jokes/random/${context.params.id}`);
  const post = await res.json()
  return { props: { post } }
}
Related