0

I am trying to log the query parameter in a Nextjs project. I never see the value logged, but the value shows up on the page. Should I just ignore that the logs in npm dev dont show the query parameter or should I handle the case where it's undefined?

/pages/test/[test].js

import {useRouter} from "next/router";
import React from "react";

const Test = () => {
    const router = useRouter();
    const {test} = router.query;
    console.log(router.query); // {}
    console.log(test);  // undefined
    return <div>
        <h1>{test}</h1>
    </div>
};
export default Test;

enter image description here

enter image description here

1 Answer 1

1

You need use useEffect with 2 dependencies:

import {useRouter} from "next/router";
import React, {useEffect, useState} from "react";

const Test = () => {
    const router = useRouter();
    const [query, setQuery] = useState(null);

    useEffect(()=>{
      setQuery(router.query)
      if (query){
        console.log(query); 
        console.log(query.test);
      } 
    },[router,query])
    
    return <div>
        <h1>{query && query.test}</h1>
    </div>
};
export default Test;

or with one dependency:

import {useRouter} from "next/router";
import React, {useEffect} from "react";

const Test = () => {
    const router = useRouter();

    useEffect(()=>{
      if (router.query){
        console.log(router.query); 
        console.log(router.query.test);
      } 
    },[router])
    
    return <div>
        <h1>{router && router.query && router.query.test}</h1>
    </div>
};
export default Test;

When you use useEffect you are sure the router has been tuned already.

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

Comments

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.