Next.js Server Actions Inside Client Components

Next.js Server Actions Inside Client Components

Today we'll do a quick exploration of Next.js Server Actions and how you can mix them into React Client Side Components.

We start with a sample app built on top of Next.js 13, the new App Router, and Supabase.

We'll submit a form and process the database update via Server Actions and then provide a response back to the Client Component. The client component can then show some feedback to the user, showing them the form was saved successfully.

Key Takeaways:

0:22 - We are using Supabase as the database and the new Next.js App Router. Data is fetched on the server via React Server Components.

1:00 - The data is passed into EditAccount, which is a Client Component, since we need to useState and update the form inputs when a user types.

1:58 - Starting off, the code to update the form runs in the Client Component. We want to move this to a Server Action.

2:53 - We copy an example from Supabase and alter it to fit our code. A Server Action will have 'use server' present in the code.

3:50 - On our HTML form element, we want to change "onSubmit" to "action" and pass in our Server Action function.

5:41 - You can run revalidatePath to update the Next.js cache, once the Server Action runs and updates the data.

5:56 - If the component is marked with "use client", you may run into errors when trying to run Server Actions. To remedy this, you can create a new file, called actions.ts, and put that next to your page.tsx file. Copy the Server Action function into this new file and move "use server" to the top of the file.

7:19 - We need to get userId into our server function

9:33 - Testing to make sure the server actions are indeed working and updating our database

10:19 - Let's enhance our Server Action so that it returns a success or error message. The Client Component can then read this response and show a toast to the user, saying their account has been updated.

Here are some code snippets seen in this video:

actions.ts: https://gist.github.com/ChangoMan/70b4da9f2286d95f6b58bf206f8d446b

EditAccount.tsx: https://gist.github.com/ChangoMan/a5413e6446c75bd8cc9829c50c2a8c0c

Did you find this article valuable?

Support Hunter Chang by becoming a sponsor. Any amount is appreciated!