Server Actions Mutation
server-actions-mutation.ts
'use server'
import db from '@/utils/db'
import { revalidatePath } from 'next/cache'
export const newTodo = async (data: FormData) => {
const newTodo = data.get('todo') as string
if (newTodo) {
await db.todo.create({
data: {
content: newTodo,
},
})
revalidatePath('/todos')
}
}
export const completeTodo = async (id: string) => {
await db.todo.update({
where: { id },
data: {
completed: true,
},
})
revalidatePath('/todos')
}
Usage
server-component.tsx
import { newTodo } from "@/utils/actions";
const NewTodoForm = () => {
return (
<div>
<form action={newTodo}>
<input type="text" name="todo" className="border border-black" />
<button type="submit">create</button>
</form>
</div>
);
};
export default NewTodoForm;
So, useTransition
is a hook that basically, you can give it some function to run, some async thing, mostly data loading, and React will de-prioritize that.
It will, you're basically telling React like this is not a priority right now,finish all the other important stuff you were doing first, before you do this.Like do this right when you're done.And we wanna do that because we don't want whatever we're about to do to block everything else that's happening on our app.We don't wanna clog that process, so we're gonna de-prioritize.
client-component.tsx
"use client";
import { completeTodo } from "@/utils/actions";
import { useTransition } from "react";
const Todo = ({ todo }) => {
const [isPending, startTransition] = useTransition();
return (
<div
className={`px-8 py-2 border border-black/25 cursor-pointer ${
todo.completed ? "line-through text-black/30" : ""
}`}
onClick={() => startTransition(() => completeTodo(todo.id))}
>
{todo.content}
</div>
);
};
export default Todo;