Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Create/Edit pages in Nextjs, should I get the product in ServerSideProps or in the component

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

like image 705
nloomis Avatar asked Oct 25 '25 04:10

nloomis


1 Answers

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.

like image 193
duggi Avatar answered Oct 26 '25 18:10

duggi