3

I am just trying to get the value of a parameter in my url.

I'm new to next.js and still fairly new to react in general.

My url looks like:

localhost:3000/?code=VhXHWwRemC32dPmm3oj0mMravO6MP3

Right now, I just am rendering a page like:

const Index = () => {
       const router = useRouter();
       const code = router.query.code;
       console.log(code);
       return(
       <div>
           <p>code: {code}</p>
           <a href={Oauth.discord_login_url}login</a>
           </div>)
        };

Just so I can see if I'm getting the code correctly from the url.

Once I log in with discord, I return to Index and the url then looks like what I showed above. I am trying to get the value of code so I can use it. What confuses me is that

<p>code: {code}</p> 

successfully displays the value of "code" on the page. But

console.log(code) 

shows undefined. Why is it different?

3
  • Does it still returns undefined if you try console.log("code: "+ code);? Commented Dec 1, 2019 at 22:10
  • Yes. It says "code: undefined". Commented Dec 1, 2019 at 23:40
  • And console.log(router.query)? Also, show a screen shot how the view looks. Thats actually strange. Commented Dec 2, 2019 at 3:38

1 Answer 1

8

Try to add getInitialProps:

const Index = () => {
  const router = useRouter();
  const code = router.query.code;
  console.log(code); 

  Index.getInitialProps = async () => {
    return {};
  };

 return ( 
   <div>
     <p>code: {code}</p> 
     <a href={Oauth.discord_login_url}>login</a>
   </div>
  ) 

};
Sign up to request clarification or add additional context in comments.

1 Comment

Oh dang. That seems to have fixed my issue. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.