Loading content...
Loading content...
👉 Simple:
Data change karna (CRUD)
Create
Update
Delete
👉 Server pe run hone wala async function
👉 Isko bolte hain:
Server Function
Server Action (form use case me)
📌 Important:
Always async
Server pe run hota hai
Client se call hota hai
👉 "use server" use karo
plaintext
export async function createPost(formData) {
"use server"
const title = formData.get("title")
// DB save
}plaintext
import { createPost } from "./actions"
export function Form() {
return (
<form action={createPost}>
<input name="title" />
<button type="submit">Create</button>
</form>
)
}👉 Form submit → direct server call
📌 Automatically POST request hota hai
plaintext
"use client"
import { createPost } from "./actions"
export default function Button() {
return <button formAction={createPost}>Create</button>
}plaintext
"use client"
import { incrementLike } from "./actions"
export default function LikeButton() {
return (
<button onClick={async () => {
await incrementLike()
}}>
Like
</button>
)
}plaintext
"use client"
import { useActionState } from "react"
const [state, action, pending] = useActionState(createPost, false)
<button onClick={action}>
{pending ? "Loading..." : "Submit"}
</button>👉 pending = loading state
👉 Data change ke baad UI update karna
plaintext
import { refresh } from "next/cache"
export async function updatePost() {
"use server"
// update DB
refresh()
}plaintext
import { revalidatePath } from "next/cache"
export async function createPost() {
"use server"
// DB save
revalidatePath("/posts")
}👉 Page fresh data show karega
plaintext
import { redirect } from "next/navigation"
export async function createPost() {
"use server"
redirect("/posts")
}👉 Action ke baad page change
plaintext
import { cookies } from "next/headers"
export async function example() {
"use server"
const cookieStore = cookies()
cookieStore.set("name", "Anil")
}👉 Get / Set / Delete cookies
Server Action = "use server"
Always async
Form → direct call
POST request automatically
Secure (server side)
After mutation:
refresh / revalidate / redirect
👉 Mutate = create/update/delete
👉 Server Action = server function
👉 "use server" = must
👉 form action = auto call
👉 revalidate = refresh data
👉 "Next.js me data change karne ke liye Server Actions use karte hain"
Form submit
Server Action call
DB update
UI refresh