CodexBloom - Programming Q&A Platform

Next.js Dynamic Routes Not Handling Query Parameters Correctly in API Calls

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
next.js react api JavaScript

Can someone help me understand I'm sure I'm missing something obvious here, but I'm currently working with an scenario with dynamic routes in my Next.js application where API calls aren't handling query parameters as expected. I have a structure like this: ```javascript // pages/[slug].js import { useRouter } from 'next/router'; const Post = () => { const router = useRouter(); const { slug } = router.query; useEffect(() => { const fetchData = async () => { const response = await fetch(`/api/posts?slug=${slug}`); const data = await response.json(); console.log(data); }; if (slug) fetchData(); }, [slug]); return <div>{slug ? `Post: ${slug}` : 'Loading...'}</div>; }; export default Post; ``` The scenario arises when I navigate directly to a URL like `/post-title` - the initial render shows 'Loading...' because `slug` is `undefined` at first. When I check the console, I see that the `fetchData` function is being called before `slug` has a value, leading to a fetch request to `/api/posts?slug=undefined`. I've tried adding a conditional check for `slug` before calling `fetchData`, but it doesn't seem to prevent the first render from triggering an API call. Additionally, I've confirmed that this works fine with static paths, so it seems to only be an scenario with dynamic routes. Is there a way to delay the API call until `slug` is fully available or should I be handling this differently? Any insights would be appreciated! This is part of a larger web app I'm building. What am I doing wrong? For context: I'm using Javascript on Ubuntu. This issue appeared after updating to Javascript latest. I'm open to any suggestions.