0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · درس

عمليات CRUD باستخدام Server Actions

نفّذ عمليات الإنشاء والقراءة والتحديث والحذف (CRUD) على قاعدة بياناتك باستخدام Server Actions

عمليات CRUD باستخدام Server Actions درس مجاني في Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Next.js 15 Fullstack (App Router + Server Actions)، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

CRUD: Database Actions Made Easy

Welcome to CRUD operations with Next.js Server Actions! CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations for interacting with any database.

Server Actions provide a powerful way to perform these operations directly on the server, keeping your client-side bundle small and improving security.

Recap: Prisma & Server Actions

In the previous lesson, we set up Prisma. We'll use Prisma Client to interact with our database. Remember, Server Actions are asynchronous functions that run on the server.

They can be defined directly in a component or in a separate actions.js file. We'll use a simple Post model for our examples.

Create: Adding New Data

Let's start with Create. This involves adding a new record to your database. We'll create a simple form that uses a Server Action to add a new post.

Notice how the form's action attribute directly calls our server function. This avoids client-side JavaScript for form submission.

Create: Code Example

Here's how to create a new post using a Server Action. We import our Prisma client and use its create method.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export default function CreatePostPage() {
  async function createPost(formData: FormData) {
    'use server';
    const title = formData.get('title') as string;
    const content = formData.get('content') as string;

    await prisma.post.create({
      data: { title, content, published: false },
    });

    revalidatePath('/posts'); // Refresh the posts list
  }

  return (
    <form action={createPost}>
      <input type="text" name="title" placeholder="Title" />
      <textarea name="content" placeholder="Content"></textarea>
      <button type="submit">Add Post</button>
    </form>
  );
}

Read: Fetching Existing Data

The Read operation retrieves data from your database. In Next.js App Router, you can fetch data directly in Server Components.

This means your data fetching logic runs on the server, before the component is sent to the client, improving initial load times.

Read: Code Example

Here's a Server Component that fetches all posts and displays them. The await prisma.post.findMany() call runs entirely on the server.

import { prisma } from '@/lib/prisma';

export default async function PostsPage() {
  const posts = await prisma.post.findMany();

  return (
    <div>
      <h1>All Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <b>{post.title}</b>
            <p>{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Update: Modifying Records

Update operations change existing records. You'll typically identify the record by its unique ID and then provide the new data.

Similar to Create, an update action can be triggered from a form submission or a button click, executing server-side logic.

Update: Code Example

This Server Action updates a post's published status. We identify the post by id and use Prisma's update method.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function updatePostStatus(id: number, published: boolean) {
  'use server';

  await prisma.post.update({
    where: { id },
    data: { published: !published },
  });

  revalidatePath('/posts');
}

// Example usage in a component:
// <button onClick={() => updatePostStatus(post.id, post.published)}>
//   Toggle Publish
// </button>

Delete: Removing Data

Finally, Delete removes a record from the database. This is often triggered by a button and requires the record's unique identifier.

Always be careful with delete operations, as they are usually irreversible!

Delete: Code Example

Here's a Server Action for deleting a post. We use prisma.post.delete with a where clause to specify which record to remove.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function deletePost(id: number) {
  'use server';

  await prisma.post.delete({
    where: { id },
  });

  revalidatePath('/posts'); // Refresh the posts list
}

// Example usage in a component:
// <button onClick={() => deletePost(post.id)}>
//   Delete Post
// </button>

CRUD Operations Check

You've learned about the four core CRUD operations. Which operation is used to retrieve existing data from the database?

Recap: CRUD with Actions

Today, you mastered performing Create, Read, Update, and Delete (CRUD) operations using Next.js Server Actions and Prisma.

  • Create: Add new records.
  • Read: Fetch records from the database.
  • Update: Modify existing records.
  • Delete: Remove records.

Server Actions make these operations efficient and secure by running them directly on the server, often requiring revalidatePath to update the UI after changes. Next, we'll explore database schema migrations!

الأسئلة الشائعة

هل درس «عمليات CRUD باستخدام Server Actions» مجاني؟

نعم — نص درس «عمليات CRUD باستخدام Server Actions» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Next.js 15 Fullstack (App Router + Server Actions)، انتقل إلى CoddyKit PRO. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.

ماذا ستتعلم في «عمليات CRUD باستخدام Server Actions»؟

نفّذ عمليات الإنشاء والقراءة والتحديث والحذف (CRUD) على قاعدة بياناتك باستخدام Server Actions تتمرن على Next.js 15 Fullstack (App Router + Server Actions) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Next.js 15 Fullstack (App Router + Server Actions)؟

لا تُشترط خبرة سابقة. Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «عمليات CRUD باستخدام Server Actions»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Next.js 15 Fullstack (App Router + Server Actions) هذا؟

نعم. كل درس في Next.js 15 Fullstack (App Router + Server Actions) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. إعداد Prisma ORM
  2. عمليات CRUD باستخدام Server Actions
  3. ترحيلات مخطط قاعدة البيانات
  4. تهيئة قاعدة البيانات وتجميع الاتصالات
← العودة إلى Next.js 15 Fullstack (App Router + Server Actions)