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.
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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With