TCS
TCS

Reputation: 799

NextJS getting url parameters returns empty at the begining

I want to get URL parameters at the begining of page, but firstly it returns empty, after a while

const rout = useRouter()
  useEffect(() => {
    console.log('queries:')
    console.log(rout.query)
  }, [rout])

It returns {} for the first time, but after a render, It returns {'myparam': 'blabla'}

How can I get URL parameter without returning an empty result?

Upvotes: 2

Views: 707

Answers (1)

Wu Wei
Wu Wei

Reputation: 2297

According to the docs, the useRouter hook from next/router returns a prop isReady, which you can check.

isReady: boolean - Whether the router fields are updated client-side and ready for use. Should only be used inside of useEffect methods and not for conditionally rendering on the server.

const rout = useRouter()
useEffect(() => {
  if (rout.isReady) {
    //rout.query will be ready here
  }
}, [rout])

Upvotes: 2

Related Questions