1

I am trying to return useRouter() variable inside useEffect().But unable to get it. getting undefined error inside the console. I actually fetching the data from API on the basis of the slug.

import { useRouter } from 'next/router';
import {useEffect, useState} from 'react'; 
import axios from "axios";
const Post = () => {
const router = useRouter();
const [snippets,SetSnippets] = useState();
const { snippet_slug } = router.query;

var config = {
headers: {
    accept: '*/*',
    'Content-Type': 'application/json',
    'API_ACCESS_KEY': 'hns2V0Ddbkkn8r1XLq3Kw7ZoiBTR0nmA',
}
};    
const url = 'api/viewsnippets';
useEffect(async ()=>{
var data = {
  slug: snippet_slug,
} 
console.log(snippet_slug); // Here i am getting error(i.e undefined)  
await axios.post(url,data,config)
.then(function (response) {
SetSnippets(response.data);
});
},[]);

return (
  <>
  {snippets && (
    <h1>{snippets.snippet_title}</h1>
  )}
  </>
);
}
export default Post;
Upasana Chauhan
  • 948
  • 1
  • 11
  • 32
  • do you have snippet_slug in your url query params ? eg: [domain]/path?snippet_slug="somevalue" – Ankush Sharma Dec 27 '21 at 07:08
  • I used POST method here – Upasana Chauhan Dec 27 '21 at 07:12
  • I mean your page url... router.query contains snippet_slug only if your page url is containing snippet_slug in query params eg: [domain]/path?snippet_slug="somevalue" – Ankush Sharma Dec 27 '21 at 07:16
  • Yes URL contains -> [domain]/path?snippet_slug="somevalue". Everything is fine on api side. I tested it on POSTMAN. Problem is I am not able to get snippet_slug inside useEffect. Might be useEffect loading before useRouter – Upasana Chauhan Dec 27 '21 at 07:21
  • Yes, useEffect loading before useRouter. Check the answer below. – Gucal Dec 27 '21 at 07:22
  • @Gucal what should i do? – Upasana Chauhan Dec 27 '21 at 07:23
  • I left an answer below. Can you try it? This is how I mostly solve this problem. But I don't know if it's best practice. – Gucal Dec 27 '21 at 07:24
  • Does this answer your question? [useRouter/withRouter receive undefined on query in first render](https://stackoverflow.com/questions/61040790/userouter-withrouter-receive-undefined-on-query-in-first-render) – juliomalves Jan 06 '22 at 21:39

3 Answers3

2

Following Code Solved My problem... Thanks all for reply

useEffect(async ()=>{
  if(!router.isReady) return;
  const { sid } = router.query;
var data = {
  slug: sid,
} 
console.log(sid);  
await axios.post(url,data,config)
.then(function (response) {
SetSnippets(response.data);
});

}, [router.isReady]);
Upasana Chauhan
  • 948
  • 1
  • 11
  • 32
  • 1
    This helped! Looks like `router` is not quite ready for the `useEffect` to use. `router.isReady` flag can be used to check if it is. – hemnath mouli Jul 06 '22 at 12:39
1
import { useRouter } from "next/navigation";

import useRouter from "next/navigation" instead of "next/router". This line of import solved my problem.

Brusooo
  • 11
  • 2
0

The error is here

const { snippet_slug } = router.query;

You have ended up renaming vs assigning the value via destructuring.

Use

const snippet_slug = router.query;

Returns an empty object on page load as defined by the docs if no querystring present , not an error

https://stackblitz.com/edit/nextjs-a2h28v?file=pages/index.js

https://nextjs-a2h28v--3000.local.webcontainer.io/?what=why - look at console

Review this post https://www.barrymichaeldoyle.com/destructuring/#:~:text=A%20Common%20Pitfall%20and%20The%20Inspiration%20for%20this%20Post

Ramakay
  • 2,919
  • 1
  • 5
  • 21