#Calling server action in a server component
1 messages · Page 1 of 1 (latest)
Hi @calm shuttle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To call a Server Action in a Server Component in Next.js, you need to define an asynchronous function with the "use server" directive at the top of the function body. This directive ensures that the function is only ever executed on the server. The function should have serializable arguments and a serializable return value.
Here is an example of how to create a Server Action in a Server Component:
export default function ServerComponent() {
async function myAction() {
'use server'
// ...
}
}
This Server Action can be defined inside the component that uses it. This is applicable to Server Components only.
For more details, you can refer to the Next.js documentation on Server Actions (https://nextjs.org/docs/app/api-reference/functions/server-actions).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@calm shuttle kapa.ai is still learning and improving, please let us know how it did by reacting below
@limpid valve What is the proper way to call that action in a server component if I want to call it once when the page loads?
Let me check the knowledge base for you. One moment! :books:
To call a Server Action when a Server Component loads in Next.js, you can call the action within the Server Component's function body. However, the extracts provided do not contain a specific example of calling a Server Action on page load within a Server Component.
Here's a general example of how you might structure it:
export default function ServerComponent() {
'use server';
async function myAction() {
// ...
}
// Call the action on load
myAction();
}