Conteúdo do Curso
Next.js 14
Next.js 14
Updating Item
Update an Invoice - Simple Steps
When updating an invoice, the process is quite similar to creating one. Here's a breakdown:
- 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; - Read the Invoice id: Grab the invoice
id
from the page parameters; - Fetch Specific Invoice: Get the information about the chosen invoice from the database;
- 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.
- Navigate to the
/invoices
folder and create a new dynamic route named[id]
; - Add a new route called' edit' inside the
/invoices/[id]
folder. Include apage.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
Obrigado pelo seu feedback!