I have a form where a user creates a product. This form uses react-hook-form to keep track of all form inputs. I'd like to reuse the form since the "Edit" page is the exact same form but with the fields filled out by data from the server.
What's the best practice is this case? Having a ProductForm component with an optional product prop? Or just copy pasting the form in two different files?
This is what I was thinking of:
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 = // Get the product with the id from the slug
return <ProductForm product={product}
}
export async function getServerSideProps({ params }) {
return {
props: { id: params.id }
}
}
The second part of my question is what the best practice is for an Edit page to get the product from the server, getServerSideProps or getStaticProps. Should I be getting the product with the id from the slug inside one of those functions? So the edit would 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 = // get product from slug id
return {
props: { product: product }
}
}
New to Nextjs so any thoughts on this are appreciated
Yes, this is exactly what you should do.
Create a single form component, then import it into the create and edit pages.
On the edit page, get the product and pass it to the form as you are doing here.
Finally, there is some logic in the form component to determine create or edit mode, and then different behavior around handling submit or other stuff.
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