'next js error when hard refresh page with dynamic query parameter
i have a next js app with dynamic page parameter, when i hard reload it in development mood it works fine , but in production i get this error 404 - File or directory not found. here is the code i use:
import { useRouter } from "next/router";
import NewsDetails from "../../../Components/news/newsDetails";
import HeadPage from "../../HeadPage";
import { GeneralLoading } from "../../../Components/ui/LoadingScreens";
import { useEffect, useState } from "react";
const Details = () => {
const [id, setID] = useState(null);
const router = useRouter();
// // fire when router.query is updated
useEffect(() => {
const { id } = router.query
console.log(id);
setID(id);
}, [router.query?.id]);
// const id = router.query['id'];
// if (!id) return null
// if(id) {
// return (
// id && <>
// <HeadPage />
// <h1>test</h1>
// <NewsDetails params={id} />
// </>
// )
// } else {
// return <h1>Test else</h1>
// }
if (!id) {
return (
<>
<div>
{" "}
<GeneralLoading />{" "}
</div>
</>
);
} else {
return (
<>
<HeadPage />
<NewsDetails params={id} />
</>
);
}
};
export default Details;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
i also tried to add this to the end of prev code , but i coudn't build and export the app then with this function inside it
export async function getStaticProps(context) {
const { id } = context.query;
// If id is "undefined", since "undefined" cannot be serialized, server will throw error
// But null can be serializable
if (!id) {
id = null;
}
// now we are passing the id to the component
return { props: { id:id } };
}
then i tried to change it to this function but also didn't work
export const getServerSideProps = async (context) => {
const { id } = context.query;
// If id is "undefined", since "undefined" cannot be serialized, server will throw error
// But null can be serializable
if (!id) {
id = null;
}
// now we are passing the id to the component
return { props: { id:id } };
};
Solution 1:[1]
when you have dynamic params you should use getStaticPaths function
NextJs wants know what exactly are this dynamic params.
use getStaticPaths like this.
export async function getStaticPaths() {
return {
paths: [
{ params: { id: 1 } },
{ params: { id: 2 } },
...
],
fallback: true, false or "blocking"
};
}
you must tell NextJs that what is your id(s) if you have to many ids set fallback to true so NextJs doesn't generate your file before page render.
see this link for more info
https://nextjs.org/docs/api-reference/data-fetching/get-static-paths
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 | Muhammad Habibpour |
