LoginSignup
5
3

More than 1 year has passed since last update.

【Next.js】useRouterのrouter.queryが初回レンダリングでundefinedになる

Posted at

やろうとしていたこと

Next.jsでURLの中のパラメータを取得。
取得したパラメータの有無によって、関数処理を分ける。

生じていた問題

確かに、目視ではパラメータがあるんです。
あるのに、どうして...
なんでだか、console.logで値を覗いてみるとundefinedが...oh..No
たしかに、次レンダリング時には値は取れてる、取れてるのだけど、その前の値(undefined)で処理が走ってしまう。

logout.jsx
const router = useRouter();
const { param } = router.query;

useEffect(()=>{
    onLogOut(); //←paramの値がundefinedでログアウト処理が進んでしまう
},[param])

解決できた方法

useRouterには、router.isReadyというオブジェクトがあるらしいです。
文字通り、routerの準備の有無が確認できました。
なので、router.isReadyを使って、routerの準備ができないうち(つまり無条件にundefinedを出す時)は、returnを返して、undefined状態で処理が進まないようにします。
準備ができたら、router.queryの中身が必要な処理をします。

logout.jsx
const router = useRouter();
const { param } = router.query;

useEffect(()=>{
  if (!router.isReady) return; //routerの準備中はここで処理がstop
    onLogOut(); //routerの準備が完了したら、ここが呼ばれる
},[param])

参考:

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3