iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
⛳

[Next.js] How to Eliminate the Initial undefined from router.query

に公開2件

The initial undefined phenomenon of query in Next.js

  • src/pages/[q].tsx
import { useRouter } from 'next/router'
import React from 'react'

const Page = () => {
  const router = useRouter()
  const q = router.query['q']
  console.log("q:",q)
  return <div>{q}</div>
}

export default Page

  • Execution result

http://localhost:3000/query

console.log result

q: undefined
q: query

Output HTML

<div></div>

If you write the program straightforwardly, the initial value is undefined, and the HTML after SSR is also empty.

Solving it instantly

When you search for a solution to this phenomenon, you might find suggestions such as returning null temporarily when it's undefined or performing the actual processing after useEffect.
In fact, it can be fixed much more easily.

Please set up the following file.

  • src/pages/_app.tsx
import App from 'next/app'
App.getInitialProps = async () => ({ pageProps: {} })
export default App

That's all.

Behavior after the fix

console.log result

q: query

Output HTML

<div>query</div>

As you can see, the undefined disappears, and SSR is performed properly after receiving the query data.

Why it works

By including getInitialProps, the query is passed to the props of the App component.
If this is not present, the query is recreated on the client side, resulting in undefined during the state transition.

There might be some reason why the query is not passed by default, but in any case, this solves the problem.

GitHubで編集を提案

Discussion

kenbukenbu

_app.tsxにgetInitialProps()入れてしまうと、全てのページがSSRになってしまうのでよくないのでは?と思いました。
https://nextjs.org/docs/api-reference/data-fetching/get-initial-props

router.isReadyを使って制御した方が良いかと。

const router = useRouter();
router.isReady // return true if ready router

https://nextjs.org/docs/api-reference/next/router

7
空雲空雲

この内容は初回のundefinedを消す方法であって、良い悪いという話が出てくるのは意図がよく分かりません。
用途によってqueryを巻き込んでSSRされたくない場合があるのならもちろん組み方を考えるべきですが、あくまで用途の問題であって良い悪いという話ではありません。

なお、Next.jsはgetInitialProps()の有無に関わりなく、もともと全てのページがSSRされます。

1