Next.js Discord

Discord Forum

why id is undeifined??

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

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

73 Replies

@Polar bear path: http://127.0.0.1:8000/?id=a output: started 0 ok server id: undefined code:
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
null
@Polar bear Click to see attachment
send full code
@Polar bear here
Polar bearOP
ok
wait a minuet
its ok, take your time
I mean
maybe just the useEffect()
try
useEffect(()=>{
  console.log('server id': id)
},[])
?
your useEffect does not have dependency array?
Polar bearOP
:o
@alfonsus ardani try tsx useEffect(()=>{ console.log('server id': id) },[]) ?
try this and see if the param is printed out
Polar bearOP
null
push
Answer
and check before using it
Polar bearOP
how to add it?
@Polar bear how to add it?
in line 68, that array
Polar bearOP
like this?
@Polar bear like this?
not in quotes
Polar bearOP
ok
like this??
like it should print even with []
Polar bearOP
hmm
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
Polar bearOP
hmm
give me pls
give you what
Polar bearOP
pull requests
Polar bearOP
ok
null
okay try putting [id] then
useEffect(()=>{
  console.log('server id': id)
},[id])
Polar bearOP
ok
hmm
o
so its not available on mount
lol okay
Polar bearOP
why print two?
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
Polar bearOP
oh
and ofc, also, at the first time the component is mounted
does it solves you problem?
Polar bearOP
no...
why don't work function?
but the id is no longer undefined right?
Polar bearOP
yes
so the question "why id is undefined" is answered right?
Polar bearOP
yep
why id is null
wt...
console.log(idd, cnt == 0 & idd)
@Yi Lon Ma and check before using it
yes you have to check if first just like he said if (idd) ....
Polar bearOP
why logged integer??
@alfonsus ardani
hmm im not sure why
maybe try to troubleshoot it
Polar bearOP
hmm