Next.js Discord

Discord Forum

why id is undeifined??

Answered
Polar bear posted this in #help-forum
Open in Discord
Avatar
Polar bearOP
path: http://127.0.0.1:8000/?id=a
output:
started 0
ok
server id: undefined 

code:
Image
Answered by Yi Lon Ma
add id in useEffect dependency
View full answer

73 Replies

Avatar
@Polar bear path: http://127.0.0.1:8000/?id=a output: started 0 ok server id: undefined code:
Avatar
the hook you need is [useSearchParams](https://nextjs.org/docs/app/api-reference/functions/use-search-params), that useRouter from next/router doesn't work in the app router
Avatar
@Polar bear Click to see attachment
Avatar
send full code
@Polar bear here
Avatar
Polar bearOP
ok
wait a minuet
Avatar
its ok, take your time
I mean
maybe just the useEffect()
try
useEffect(()=>{
  console.log('server id': id)
},[])
?
Avatar
your useEffect does not have dependency array?
Avatar
Polar bearOP
:o
Avatar
@Alfonsus Ardani try tsx useEffect(()=>{ console.log('server id': id) },[]) ?
Avatar
try this and see if the param is printed out
Avatar
Polar bearOP
Image
null
push
Answer
Avatar
and check before using it
Avatar
Polar bearOP
how to add it?
Avatar
@Polar bear how to add it?
Avatar
in line 68, that array
Avatar
Polar bearOP
like this?
Image
Avatar
@Polar bear like this?
Avatar
not in quotes
Avatar
Polar bearOP
ok
Image
like this??
Avatar
like it should print even with []
Avatar
Polar bearOP
hmm
Avatar
and i didnt see console.log() outside of the conditionals
and codesandbox is giving me a hard time with next.js so i can't give you a demo right now
Avatar
Polar bearOP
hmm
give me pls
Avatar
give you what
Avatar
Polar bearOP
pull requests
Avatar
Polar bearOP
ok
null
Image
Avatar
okay try putting [id] then
useEffect(()=>{
  console.log('server id': id)
},[id])
Avatar
Polar bearOP
ok
Image
hmm
Avatar
o
so its not available on mount
lol okay
Avatar
Polar bearOP
why print two?
Avatar
coz first is component on mount
then second is when id value changed
its called a dependency array so the useEffect is run when the value inside that array changed
Avatar
Polar bearOP
oh
Avatar
and ofc, also, at the first time the component is mounted
does it solves you problem?
Avatar
Polar bearOP
no...
why don't work function?
Avatar
but the id is no longer undefined right?
Avatar
Polar bearOP
yes
Avatar
so the question "why id is undefined" is answered right?
Avatar
Polar bearOP
yep
why id is null
wt...
console.log(idd, cnt == 0 & idd)
Image
Avatar
@Yi Lon Ma and check before using it
Avatar
yes you have to check if first just like he said if (idd) ....
Avatar
Polar bearOP
Image
why logged integer??
@Alfonsus Ardani
Avatar
hmm im not sure why
maybe try to troubleshoot it
Avatar
Polar bearOP
hmm