Reputation: 261
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");
});
};
Upvotes: 9
Views: 5600
Reputation: 93
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')
Upvotes: -1
Reputation: 404
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: {},
};
}
Upvotes: 9