๐
๐ Next.js Mutating Data (Easy Notes)
๐ 1. Mutating Data kya hota hai?
๐ Simple:
Data change karna (CRUD)
Create
Update
Delete
โก 2. Server Function kya hota hai?
๐ Server pe run hone wala async function
๐ Isko bolte hain:
Server Function
Server Action (form use case me)
๐ Important:
Always
asyncServer pe run hota hai
Client se call hota hai
๐น Kaise banaye?
๐ "use server" use karo
export async function createPost(formData) {
"use server"
const title = formData.get("title")
// DB save
}๐ง 3. Server Action ka Use (Form me)
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
๐ป 4. Client Component se call kaise kare?
"use client"
import { createPost } from "./actions"
export default function Button() {
return <button formAction={createPost}>Create</button>
}๐ฅ 5. Event Handler se call
"use client"
import { incrementLike } from "./actions"
export default function LikeButton() {
return (
<button onClick={async () => {
await incrementLike()
}}>
Like
</button>
)
}โณ 6. Loading State (Pending)
"use client"
import { useActionState } from "react"
const [state, action, pending] = useActionState(createPost, false)
<button onClick={action}>
{pending ? "Loading..." : "Submit"}
</button>๐ pending = loading state
๐ 7. Data Refresh (Important)
๐ Data change ke baad UI update karna
import { refresh } from "next/cache"
export async function updatePost() {
"use server"
// update DB
refresh()
}โป๏ธ 8. Cache Revalidate
import { revalidatePath } from "next/cache"
export async function createPost() {
"use server"
// DB save
revalidatePath("/posts")
}๐ Page fresh data show karega
๐ 9. Redirect after Action
import { redirect } from "next/navigation"
export async function createPost() {
"use server"
redirect("/posts")
}๐ Action ke baad page change
๐ช 10. Cookies Handle
import { cookies } from "next/headers"
export async function example() {
"use server"
const cookieStore = cookies()
cookieStore.set("name", "Anil")
}๐ Get / Set / Delete cookies
๐ง 11. Important Rules (Interview)
Server Action =
"use server"Always async
Form โ direct call
POST request automatically
Secure (server side)
After mutation:
refresh / revalidate / redirect
๐ฅ Short Revision (1 min)
๐ Mutate = create/update/delete
๐ Server Action = server function
๐ "use server" = must
๐ form action = auto call
๐ revalidate = refresh data
๐ฅ Super Simple Line
๐ "Next.js me data change karne ke liye Server Actions use karte hain"
๐ Full Flow เคธเคฎเค เคฒเฅ
Form submit
Server Action call
DB update
UI refresh