Reputation: 29
I don't understand the importance of Server Actions in Next.js. For example take a look at the following code.
import prisma from '@/utils/db';
const PrismaExamplePage: React.FunctionComponent = async() => {
await prisma.task.create({
data: {
name: 'Testing Something Out Right Now.'
}
});
return (
<h1>Prisma Example Page</h1>
);
}
export default PrismaExamplePage;
Everything works. Then I see people do the same thing using Server Actions
import prisma from '@/utils/db';
const createTask = async() => {
"use server";
await prisma.task.create({
data: {
name: 'Testing Something Out Right Now.'
}
});
}
const PrismaExamplePage: React.FunctionComponent = async() => {
await createTask();
return (
<h1>Prisma Example Page</h1>
);
}
export default PrismaExamplePage;
What is the difference between me using Server Actions and not using Server Actions. I don't see the benefit or the point
I've heard some people argue that it makes the code readable but thats not a good answer. Because I can also make the code more readable and not use a server action.
import prisma from '@/utils/db';
const createTask = async() => {
await prisma.task.create({
data: {
name: 'Testing Something Out Right Now.'
}
});
}
const PrismaExamplePage: React.FunctionComponent = async() => {
await createTask();
return (
<h1>Prisma Example Page</h1>
);
}
export default PrismaExamplePage;
Upvotes: 1
Views: 1099
Reputation: 974
Your example code renders on the server. If you want to createTask()s
in client components (forms action, event handlers, ...) you are already done and can use your server action. Without, you would need an API.
Server Actions are asynchronous functions that are executed on the server.
One strong use case is Server Actions as form actions. Just see how comfortable one can use forms. I won't repeat the manual here but recommend reading the forms examples.
They are not limited to use with forms. Event handlers are another use case.
Well designed Server Actions integrate seamless with modern React and Next.js, another advantage over other solutions.
At the end of the day it's up to you, your knowledge, your tools you are comfortable with and the app you develop if you want to use Server Actions.
Upvotes: 0
Reputation: 441
some benefit of server actions :
Upvotes: 1