Home > other >  How to send request to server only when URL param is loaded? [ Next.JS ]
How to send request to server only when URL param is loaded? [ Next.JS ]

Time:11-26

In the Next.js I'm working,you can get a post in the route /posts/[id].tsx ,I am using react-query to make the get request. I get the postId with

const {id}=router.query

But everytime I enter the page it sends the request to the server with undefined ,and also, do you guys know how to disable the React property of sending twice the requests when we enter a page? I think it is a waste of processing (correct me if I'm wrong please) Thank you for reading until here !!!

CodePudding user response:

You can use useEffect to check if the id is available, then run the rest of your code.

useEffect(() => {
    if (!id) return;
    console.log(id);
}, [id]);

If reactStrictMode in the next.config.js file is set to true, it will run your code twice. This is only in development mode.

CodePudding user response:

to extract the value we can use a hook called useRouter from next/router. if we have a file called [newsId].tsx , we can get newsId value in the following manner.

//[newsId].tsx
    import {useRouter} from 'next/router

function DetailPage(){
const router = useRouter();

//gives us the value in url

console.log(router.query.newsId;)

return <h1>hello</h1>
}
export default DetailPage

note that the double values where one is undefined is because the component is loaded initially without the value then again when it gets the value. If you want it to render once you can refer to this answer. useRouter/withRouter receive undefined on query in first render

  • Related