Next.js 15 Fullstack (App Router + Server Actions) · บทเรียน

ฟอร์ม Server Action พื้นฐาน

สร้างฟอร์มแบบโต้ตอบที่ส่งข้อมูลไปยังเซิร์ฟเวอร์โดยตรงด้วย Next.js Server Actions

บทเรียน 1 จาก 410 ขั้นตอน

ฟอร์ม Server Action พื้นฐาน เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack (App Router + Server Actions) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to Server Actions

Welcome to Server Actions! This powerful Next.js 15 feature allows you to define functions that run directly on the server, callable from your client components.

Think of them as a way to send data to your server without needing to create a separate API route. They simplify data mutations and form submissions.

Why Use Server Actions?

Server Actions offer several key benefits for your Next.js applications:

  • Simplified Data Mutations: Directly call server-side code from your forms.
  • Reduced Client-Side JS: Less JavaScript needs to be sent to the browser.
  • Improved Performance: Actions run closer to your database, potentially reducing latency.
  • Automatic Revalidation: They can automatically update cached data after a successful mutation (more on this in a later lesson!).

Defining a Server Action

A Server Action is an async function marked with the "use server" directive. This directive tells Next.js to treat the function as server-only code.

You can define actions directly in your components or in a separate file (e.g., app/actions.js) and import them.

// app/actions.js
"use server";

export async function createItem(formData) {
  const itemName = formData.get("itemName");
  console.log(`Server received: ${itemName}`);
  // In a real app, you'd save 'itemName' to a database
}

Connecting Form to Action

To link an HTML <form> element to a Server Action, you simply pass the action function directly to the form's action prop. It's that easy!

When the form is submitted, Next.js automatically invokes the specified Server Action.

// app/page.js
import { createItem } from './actions';

export default function Page() {
  return (
    <form action={createItem}>
      <label htmlFor="item">New Item:</label>
      <input type="text" id="item" name="itemName" required />
      <button type="submit">Add Item</button>
    </form>
  );
}

Accessing Form Data

When a form submits to a Server Action, the action function automatically receives a FormData object as its first argument.

You can use formData.get('fieldName') to retrieve the value of an input based on its name attribute.

// app/actions.js
"use server";

export async function processForm(formData) {
  const username = formData.get("username");
  const email = formData.get("email");
  const age = formData.get("age");

  console.log(`User: ${username}, Email: ${email}, Age: ${age}`);
  // Perform server-side logic, e.g., save user to database
}

Full Form Example

Let's combine what we've learned into a simple guestbook entry form. The Server Action will log the guest's message.

Remember, this code is for a Next.js environment and isn't runnable as a standalone JS file.

// app/actions.js
"use server";

export async function addGuestbookEntry(formData) {
  const message = formData.get("message");
  console.log(`New guestbook entry: ${message}`);
  // In a real app, save to DB and revalidate cache
}

// app/page.js
import { addGuestbookEntry } from './actions';

export default function GuestbookPage() {
  return (
    <div>
      <h1>Guestbook</h1>
      <form action={addGuestbookEntry}>
        <textarea name="message" rows="4" cols="30" placeholder="Your message..." required></textarea>
        <button type="submit">Sign Guestbook</button>
      </form>
    </div>
  );
}

Handling Multiple Inputs

The FormData object efficiently captures all inputs within your form that have a name attribute. You can access them individually.

  • formData.get('inputName'): Gets the first value for a given name.
  • formData.getAll('inputName'): Returns an array of all values for inputs with the same name (useful for multiple checkboxes).
  • formData.entries(): Returns an iterator for all key/value pairs.

User Feedback: Loading States

When a form is submitting, it's good practice to provide visual feedback to the user. Next.js, along with React, provides the useFormStatus hook for this.

useFormStatus tells you if the parent <form> is currently submitting, allowing you to disable buttons or show a spinner.

// app/page.js (inside a component, e.g., SubmitButton.js)
import { useFormStatus } from "react-dom";

function SubmitButton() {
  const { pending } = useFormStatus(); // Gets status from parent <form>

  return (
    <button type="submit" disabled={pending}>
      {pending ? "Submitting..." : "Submit"}
    </button>
  );
}

// In your page.js:
// import { addGuestbookEntry } from './actions';
// export default function Page() {
//   return (
//     <form action={addGuestbookEntry}>
//       {/* ... other inputs */}
//       <SubmitButton />
//     </form>
//   );
// }

Quick Check

Which statements about basic Next.js Server Action forms are correct?

Recap & Next Steps

Great job! You've learned the fundamentals of creating basic forms with Next.js Server Actions:

  • Server Actions are server-side functions marked with "use server".
  • They simplify form submissions by allowing you to pass the action directly to a form's action prop.
  • Form data is accessed within the action via a FormData object.
  • The useFormStatus hook helps implement loading indicators.

Next, we'll dive into how Server Actions can mutate data and automatically revalidate your UI!

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
22
บทเรียน
88

คำถามที่พบบ่อย

บทเรียน “ฟอร์ม Server Action พื้นฐาน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ฟอร์ม Server Action พื้นฐาน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack (App Router + Server Actions) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ฟอร์ม Server Action พื้นฐาน”

สร้างฟอร์มแบบโต้ตอบที่ส่งข้อมูลไปยังเซิร์ฟเวอร์โดยตรงด้วย Next.js Server Actions คุณปฏิบัติ Next.js 15 Fullstack (App Router + Server Actions) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack (App Router + Server Actions) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack (App Router + Server Actions) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “ฟอร์ม Server Action พื้นฐาน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack (App Router + Server Actions) นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack (App Router + Server Actions) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ฟอร์ม Server Action พื้นฐาน
  2. การเปลี่ยนแปลงข้อมูลและการตรวจสอบใหม่
  3. การจัดการข้อผิดพลาดในแอ็กชัน
  4. ส่วนติดต่อผู้ใช้แบบมองโลกในแง่ดีและสถานะรอดำเนินการด้วยการกระทำฝั่งเซิร์ฟเวอร์
← กลับไปที่ Next.js 15 Fullstack (App Router + Server Actions)