Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nextJS SSR useRouter() does not work when refresh page

I am using nextJS SSR in my project. Now when I try to use the following code to get page parameters then it shows undefined.

 function About() {
  const router = useRouter();
  const { plan_id } = router.query;
  console.log(plan_id)
 }
 export default About;

It works when the page is routed from some other page (without page reload with "next/link") but it does not work when I refresh the page. Can someone please help?

like image 834
Nitesh Malviya Avatar asked Sep 01 '20 16:09

Nitesh Malviya


People also ask

How do I use NextJs useRouter?

Method 1: Using useRouter() Method: In NextJs we can easily get the value of the current route using the useRouter() function. To use this we are going to create a new page inside our pages directory with the name 'get-route. js'. After that, we will add the below code in our get-route.

What is router isReady?

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. See related docs for use case with automatically statically optimized pages.

What is shallow routing in NextJs?

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps , getStaticProps , and getInitialProps . You'll receive the updated pathname and the query via the router object (added by useRouter or withRouter ), without losing state.

Can I use react router in NextJs?

Steps. In React JS, we would install a package called react-router-dom to implement routing inside the application. But Next JS has its own inbuilt router from the next/link , with which we can navigate between the pages. Before using the next/link , we need to set up the different pages/routes inside the pages folder.


1 Answers

I found the answer self. Actually when you refresh the page then the router does not get initialized instantly. So you can add that under UseEffect hook as following and you will be able to get the parameters

function About() {

 const [param1, setParam1]=useState("");
 const router = useRouter();

 useEffect(() => {
  if (router && router.query) {
   console.log(router.query);
   setParam1(router.query.param1);
  }
 }, [router]);
}

When this router parameter will change then it will call the "UseEffect" which can be used to retrieve the values.

like image 86
Nitesh Malviya Avatar answered Sep 28 '22 15:09

Nitesh Malviya