I will make it simple:
Link: http://localhost:3000/product/bioCloths?activeCategory=medium&id=0
File path: pages/product/[product].js
.
Expected: product: "bioCloths, activeCategory: "medium", id: "0"
using getStaticProps
at [product].js
:
const ProductDetails = (props) => {
console.log("initial props", props);
return <div>product details...</div>
};
export default ProductDetails;
export async function getStaticProps(context) {
return {
props: {
context: context
},
};
}
export async function getStaticPaths() {
return {
paths: [{ params: { product: "1" } }, { params: { product: "2" } }],
fallback: true,
};
}
Props
returns: context: params: product: "bioCloths"
, excluding the query params.
Now if I use the deprecated getInitialProps
instead:
ProductDetails.getInitialProps = (context) => {
const activeCategory = context.query.activeCategory;
const id = context.query.id;
const product = context.query.product;
return {
activeCategory: activeCategory,
id: id,
product: product,
};
};
props logs activeCategory: "medium" id: "0" product: "bioCloths"
I need to get these all of these props so I can fetch
data before the client mounts.
I understand that getInitialProps
is now deprecated, but it works. Why is not getStaticProps
working, and should I use it instead of serverSideProps
?
This is an ecommerce, and there is no way I can set getStaticPaths
for hundreds of possibilities, to work along with getStaticProps
so I guess that in this case I should use getInitialProps or getServerSideProps
?
P.S - getServerSideProps
hits me an error stating that it will only accept .json
files.
According to one of the maintainers of Nextjs
this is the reply for anyone learning this framework:
getStaticProps
generates the page at build time. There's no possible way to know the custom query params your visitors can use at build time.
getInitialProps
andgetServerSideProps
can know all the possible query params because the page is generated at runtime, whenever you receive a new request.
You can learn more about the above here.
"
This discussion can be read on Github
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