Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Updating Item | Advanced Features
Next.js 14
course content

Conteúdo do Curso

Next.js 14

Next.js 14

1. Introduction
2. Basic Concepts
3. Pages and Layouts
4. Deployment and Database
5. Working with Data
6. Advanced Features
7. Authentication

bookUpdating Item

Update an Invoice - Simple Steps

When updating an invoice, the process is quite similar to creating one. Here's a breakdown:

  1. Create a Dynamic Route: Create a new dynamic route segment, including the invoice id. This way, we tell the app which invoice we are working with;
  2. Read the Invoice id: Grab the invoice id from the page parameters;
  3. Fetch Specific Invoice: Get the information about the chosen invoice from the database;
  4. Update Database: After making any necessary changes, update the invoice data in the database.

Back to the Project

1. Create a Dynamic Route

Based on changing data, we can make Dynamic Route Segments when we want flexible routes. Wrap a folder's name in square brackets to create a dynamic route. For instance, use [id], [post], or [slug] when we want variable segments in the route.

  1. Navigate to the /invoices folder and create a new dynamic route named [id];
  2. Add a new route called' edit' inside the /invoices/[id] folder. Include a page.tsx.

Result:

Let's examine the Table component in app/ui/invoices/table.tsx. We can observe that UpdateInvoice receives the invoice id.

Go to the <UpdateInvoice /> (app/ui/invoices/buttons.tsx) component. We see that we use the id as a part of the href value.

2. Read the Invoice id

Insert the follwoing code into app/dashboard/invoices/[id]/edit/page.tsx.

3. Fetch Specific Invoice

Next, we import new functions called fetchInvoiceById and fetchSellers.

  • fetchInvoiceById returns data for a specific invoice;
  • fetchSellers returns sellers for the form dropdown showing all sellers.

We can efficiently fetch both the invoice and sellers simultaneously using Promise.all.

Let's test it! We can open the invoices page and click the edit button (pen symbol). This should redirect us to the form with a prefilled invoice.

4. Update Database

We need to send the id to the Server Action to update the correct record in the database. Here's how you can do it effectively:

Employ JS bind to pass the id to the Server Action. This ensures that any values sent to the Server Action are appropriately encoded.

Avoid passing id as an argument directly in the form action like this:

Next, we will proceed with the actions and create an action for updating the invoice.

Try it out! After editing an invoice, submit the form, and you should be redirected to the invoices page with the updated invoice.

In Practice

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 6. Capítulo 6
some-alt