What is the best approach for managing Create/Edit pages in Next.js - should I fetch the product data in ServerSideProps or directly in the component?

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

Answer №1

Absolutely, following these steps will guide you in the right direction.

Develop a unified form component and subsequently integrate it into both the create and edit interfaces.

When editing, retrieve the product data and transmit it to the form as demonstrated here.

Lastly, customize the form component with logic to distinguish between creation and editing modes, leading to varied actions upon submission or other tasks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that a Material UI transition component fully occupies the space of its parent component?

I've been experimenting with a Material UI transition component in an attempt to make it completely fill its parent container. So far, I've achieved some success by setting the width and height to 100% and applying a Y-axis translation for the co ...

Hide the Select Column from the material-react-table

Can someone help me with hiding specific columns in the material-react-table component? I've searched the documentation but couldn't find any relevant information. import { useMemo, useState } from "react"; import { MaterialReactTable } ...

Click to Rotate Angular Chevron

Is it possible to animate the rotation of a chevron icon from left-facing to right-facing using Angular? CSS: .rotate-chevron { transition: .1s linear; } HTML: <button [class.button-open]="!slideOpen" [class.button-close]="slideOpe ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

What is the significance of receiving an error in Internet Explorer when running the code below?

function checkStepValidity(isValid, dataModel) { if (isValid) { updatedDataModel = mergeObjects(this.updatedDataModel, dataModel); } }, The code above encounters the following error in Internet Explorer / Edge browse ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

Assistance with JSONP (Without the use of jQuery)

I've been putting in a lot of effort trying to understand how to make a JSONP request, but all the reference materials I find are full of jQuery examples. I can go through the jQuery source code, but I prefer a straightforward and simple example. I&ap ...

How about displaying the Ajax response as an image?

I'm working on a script that pulls an image link, which seems to be functioning correctly. However, I am struggling with how to display the link as an image. Can someone please assist me with this? <script src="//ajax.googleapis.com/ajax/li ...

Adding elements to a two-dimensional array using AngularJS

How can I assign the value of an input to tasks.name and automatically set status: false when adding a new item to the $scope.tasks array? HTML <input type="text" ng-model="typeTask"> <button ng-click="updateTasks()">Add task</button> ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

Easily choose multiple items at once by searching with react-select

I have implemented react-select to showcase a searchable drop-down list of items where users can select multiple items. The list is lengthy, and users often find it tedious to multi-select many items that match the same filter string. This is because each ...

JavaScript plugin specifically designed to enable playback of media content, such as videos from

I am working on a spring-based project and I require the ability to play audio/video in various formats similar to YouTube. I am currently searching for a free JS plugin that would be the best fit for my needs. Any suggestions or recommendations would be ...

The JavaScript-rendered HTML button is unresponsive

I have a JavaScript function that controls the display of a popup window based on its visibility. The function used to work perfectly, with the close button effectively hiding the window when clicked. However, after making some changes to the code, the clo ...

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

A tutorial on creating a fixed header in Next.js using the useEffect hook

Currently, I am developing a website using next.js. My goal is to create a fixed header that remains in place as the user scrolls down the page. Although I am still getting familiar with the concept of useEffect, I decided to try an experiment: export fun ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

Utilizing Foundation and jQuery in a Next.js web development project

I've been attempting to incorporate Zurb Foundation's scripts into my next js application, but I keep encountering an error message when trying to include the Foundation core. The error I'm seeing is: /Users/alasdair_macrae/Sites/merlin/spa_ ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...