'ID is gone when I refresh a NextJS Dynamic Route page
I am trying to get dynamic routing working in order to display and retrieve the right information using the id from the url. This works when I visit the page, but when I reload the page the id is blank. Is this fixable? I couldn't find a answer for it on the internet.
Any help would be appreciated.
Code for reference
//Initializing router
const router = useRouter();
//Getting id from url
const { id } = router.query;
//Fetching postdata
const getPostData = async () => {
setLoading(true);
await db
.collection("Posts")
.doc(id)
.get()
.then(function (doc) {
if (doc.exists) {
setPostData(doc.data());
setLoading(false);
} else {
//router.push("/404");
}
})
.catch(function (error) {
//router.push("/404");
});
};
Solution 1:[1]
This is a known caveat about Next.js routing, you can read about it here.
Anyway, add this on your page that uses router.query:
export async function getServerSideProps(context) {
return {
props: {},
};
}
Solution 2:[2]
You can save to localstorage the id the first time, and get that item if query.id is undefined, look at this approach:
query.id && localStorage.setItem('lastId', query.id)
const id = query.id || localStorage.getItem('lastId')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mihai Moraru |
Solution 2 | Francisco Enrique Giménez Vera |