Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js dynamic route parameter is undefined

The problem

In my Next.js app I want to use the value of a dynamic route to fetch some html via http and use the result on the page.

For example, the Next route

/test

should result in an http request to

https://blobstorage.com/test.html

The issue I have is that when I make the api call, the route value is undefined so I end up making a http request to https://blobstorage.com/undefined.html

Note: To be clear here, the issue is that the value is not available at the point I render the page. This question is not asking how I can get the value from the router.

Code example

export default function Home() {

  const [html, setHtml] = useState('')
  const router = useRouter()

  useEffect(() => {

    const { url } = router.query

    setHtmlText(url)
    
    async function setHtmlText(htmlUrl) {
      const result = await fetch(`https://blobstorage.com/${htmlUrl}.html`)
      const htmlText = await result.text()
      setHtml(htmlText);
    }
  }, [])

  function createMarkup() {
    return {__html: html};
  }

  return (
    <div>
      {html && <div dangerouslySetInnerHTML={createMarkup()} ></div>}
    </div>    
  )
}

I don't know how to render the page only when the value from the route is available. Could someone help me here please?

like image 328
Vinyl Warmth Avatar asked Mar 11 '26 17:03

Vinyl Warmth


1 Answers

You can use the page structure for dynamic routing like : url/[slug].js and get the router.query.slug once the parameter router.isReady is true.

 useEffect(() => {
    if(router.isReady){
      const urlPath = router.query.slug;
      
      setHtmlText(urlPath)
    
    async function setHtmlText(htmlUrl) {
      const result = await fetch(`https://blobstorage.com/${htmlUrl}.html`)
      const htmlText = await result.text()
      setHtml(htmlText);
    }
    }
  }, [router.isReady]);
  
like image 81
Anish Antony Avatar answered Mar 14 '26 09:03

Anish Antony