Currently, I am working on a form that allows users to create a product. This form is equipped with react-hook-form to efficiently manage all the inputs. I am considering reusing this form for the Edit page since it shares the same fields, but the data will be pre-filled from the server.
What do you think would be the best approach in this scenario? Should I create a ProductForm
component with an optional product
prop? Or should I simply duplicate the form in two separate files?
The structure I have in mind is as follows:
pages/product/create/index.tsx
export default function Create() {
return <ProductForm />
}
pages/product/create/edit.tsx
export default function Edit({id}: {id: number}) {
const product = // Retrieve the product using the id
return <ProductForm product={product}
}
export async function getServerSideProps({ params }) {
return {
props: { id: params.id }
}
}
Another aspect I'm contemplating is the best practice for fetching the product data for the Edit page - through getServerSideProps
or getStaticProps
. Should I fetch the product based on the slug's id within these functions? So the edit page could look something like this instead
pages/product/create/edit.tsx
export default function Edit({product}: {product: Product}) {
return <ProductForm product={product}
}
export async function getServerSideProps({ params }) {
const product = // retrieve product using slug id
return {
props: { product: product }
}
}
I'm new to Next.js so any insights on this matter are highly valued