Learn Remix · 4/13

Data Mutation: Forms and Actions

10 min read

So, you've learned how to fetch and display data in your Remix app. That's fantastic! 👏 But what happens when you want to change that data? How do you let users create new posts, update their profiles, or delete that embarrassing photo from last year's holiday party?

That, my friend, is where Data Mutation comes in.

What is Data Mutation? 🤔

Definition: In the simplest terms, data mutation is the process of changing data. This includes creating new data (Create), updating existing data (Update), or deleting data (Delete). Think of it as the "write" operations, while fetching data is the "read" operation.

The Problem Before We Begin

Imagine you have a simple blog. You can see all the posts, which is great. But how do you write a new one?

In the old days of the web, you'd have a basic HTML <form>. When a user filled it out and hit "submit," the entire browser would refresh. The data would be sent to the server, the server would process it, and then send back a whole new page. It was a bit clunky and slow, like sending a letter by carrier pigeon every time you wanted to say something new. 🕊️

Modern web apps feel faster because they handle these changes without a full page reload. This is where Remix's approach to forms and actions shines. It gives you the progressive enhancement of a classic HTML form with the smooth user experience of a modern single-page application (SPA), right out of the box.

Let's dive into how Remix makes this happen!


1. The Remix <Form> Component: Enhancing Native HTML Forms 📝

At its core, Remix uses the standard HTML <form> element, but with a supercharge. You don't import a fancy, complicated component; you import <Form> directly from Remix.

Definition: The Remix <Form> component is a wrapper around the standard HTML <form> that intercepts the browser's request when the form is submitted. Instead of a full-page reload, it uses a client-side fetch request, making the user experience much smoother.

Think of it like upgrading from a manual car to an automatic. You're still driving, but a lot of the clunky, manual work (the full-page refresh) is handled for you, resulting in a smoother ride.

How it Works (Under the Hood):

When a user submits a Remix <Form>, Remix prevents the browser's default behavior. It then mimics the browser's request using the JavaScript fetch API in the background. This means all the data is sent to your server, but the user's screen doesn't go white during a page reload. It's the best of both worlds: the reliability of a server-rendered app with the feel of a client-side app.

Example: A Simple "New Post" Form

Let's create a form to add a new post to our blog.

jsx
// app/routes/posts.new.jsx
import { Form } from "@remix-run/react";

export default function NewPost() {
  return (
    <Form method="post">
      <p>
        <label>
          Post Title: <input type="text" name="title" />
        </label>
      </p>
      <p>
        <label>
          Post Body: <textarea name="body" />
        </label>
      </p>
      <p>
        <button type="submit">Create Post</button>
      </p>
    </Form>
  );
}

This looks almost exactly like a regular HTML form, right? The key differences are:

  1. We're importing Form from @remix-run/react.
  2. We've set method="post". This is crucial. A post method tells Remix that we intend to change data.

When this form is submitted, Remix will send a POST request to the current route's URL (/posts/new in this case). But where does that request go? Let's find out.


2. The action Function: Handling POST Requests on the Server сервер

Definition: An action function is a server-side function that you export from a route module. It's designed to handle non-GET requests (like POST, PUT, PATCH, DELETE) that are sent to that route. This is where your data mutation logic lives.

The Problem it Solves: You need a specific place on the server to catch the data submitted from your form, process it, and interact with your database or any other service. The action function is Remix's designated "inbox" for these requests.

Imagine you're at a drive-thru. You give your order (the form submission) to the speaker. The person inside the restaurant (the action function) takes that order, prepares your food (processes the data), and then gives it to you. The action is the worker who "acts" on your request.

How to Implement an action:

Let's add an action function to our posts.new.jsx route to handle the form submission.

jsx
// app/routes/posts.new.jsx
import { Form } from "@remix-run/react";
import { createPost } from "~/models/post.server"; // A fictional function to save the post

export async function action({ request }) {
  const formData = await request.formData();
  const title = formData.get("title");
  const body = formData.get("body");

  // Here you would typically save the data to your database
  await createPost({ title, body });

  // For now, let's just log it to see it work
  console.log({ title, body });

  return null; // We'll improve this later!
}

export default function NewPost() {
  // ... our Form from before
  return (
    <Form method="post">
      {/* ... form inputs ... */}
    </Form>
  );
}

Breaking it Down:

  • export async function action({ request }): We define and export an async function named action. Remix automatically passes a request object to it, which contains all the details of the submission.
  • const formData = await request.formData();: This line is pure web standards! It parses the form data from the request.
  • formData.get("title") and formData.get("body"): We extract the values from the form fields based on their name attributes. This is why giving your inputs a name is so important!

Now, when you fill out the form and click "Create Post", the browser will not refresh. Instead, your server-side terminal (where you ran npm run dev) will log the title and body you entered. Success! 🎉


3. Validating Form Data and Returning Errors to the UI 🧐

The Problem: What if a user tries to submit a form with an empty title? Or a password that's too short? You can't just blindly trust user input. You need to validate it on the server and, if there's a problem, tell the user what the problem is so they can fix it.

This is like a quality check in a factory. Before a product is shipped (saved to the database), you inspect it for defects (validation errors). If you find a defect, you send it back with a note explaining what needs to be fixed.

How Remix Handles Validation:

Remix has a built-in hook called useActionData that allows your action function to send data back down to your component. This is perfect for returning validation errors.

Example: Adding Validation to Our Action

Let's update our action to require a title and a body.

jsx
// app/routes/posts.new.jsx
import { json } from "@remix-run/node"; // Important: Remix's json helper
import { Form, useActionData } from "@remix-run/react";
import { createPost } from "~/models/post.server";

export async function action({ request }) {
  const formData = await request.formData();
  const title = formData.get("title");
  const body = formData.get("body");

  const errors = {};
  if (typeof title !== "string" || title.length === 0) {
    errors.title = "Title is required";
  }
  if (typeof body !== "string" || body.length === 0) {
    errors.body = "Body is required";
  }

  // If there are any errors, return them.
  if (Object.keys(errors).length > 0) {
    return json(errors, { status: 400 }); // Return errors as JSON with a 400 status
  }

  await createPost({ title, body });

  // If successful, we'll deal with this next!
  return null;
}

export default function NewPost() {
  const errors = useActionData();

  return (
    <Form method="post">
      <p>
        <label>
          Post Title: <input type="text" name="title" />
        </label>
        {errors?.title ? <em style={{ color: "red" }}>{errors.title}</em> : null}
      </p>
      <p>
        <label>
          Post Body: <textarea name="body" />
        </label>
        {errors?.body ? <em style={{ color: "red" }}>{errors.body}</em> : null}
      </p>
      <p>
        <button type="submit">Create Post</button>
      </p>
    </Form>
  );
}

What's Happening Here?

  1. Server-Side (action):

    • We create an errors object.
    • We check our fields. If a field is invalid, we add a message to the errors object.
    • Crucially: If the errors object has any keys, we return json(errors). This sends the error object back to the browser. Using a { status: 400 } is a good practice, indicating a "Bad Request".
  2. Client-Side (NewPost component):

    • const errors = useActionData();: We call the useActionData hook. After a form submission, this hook will contain whatever data the action function returned. If the form hasn't been submitted yet, or if the action returned null, errors will be undefined.
    • {errors?.title ? ...}: We then conditionally render the error messages right next to the corresponding form fields. The optional chaining (?.) is important to prevent errors when the errors object is undefined.

Now, if you try to submit an empty form, you'll see your error messages appear instantly, without a page refresh! This is a huge win for user experience. ✨


4. Redirects: Navigating the User After Successful Mutations ↪️

The Problem: Our form now handles validation, but what happens after a successful submission? Right now, our action just returns null. The user stays on the "New Post" page, which is confusing. Did it work? Should they submit again?

After a user successfully creates something, you should usually take them somewhere else. For example, after creating a new blog post, you should probably redirect them to the page for that new post, or back to the main blog page.

Remix's redirect Helper:

Remix provides a simple redirect utility to handle this common pattern.

Example: Redirecting on Success

Let's complete our action function. We'll assume our createPost function returns the newly created post, which has a slug we can use for the URL.

jsx
// app/routes/posts.new.jsx
import { json, redirect } from "@remix-run/node"; // Add redirect
import { Form, useActionData } from "@remix-run/react";
import { createPost } from "~/models/post.server";

export async function action({ request }) {
  const formData = await request.formData();
  const title = formData.get("title");
  const body = formData.get("body");

  const errors = {};
  if (typeof title !== "string" || title.length === 0) {
    errors.title = "Title is required";
  }
  if (typeof body !== "string" || body.length === 0) {
    errors.body = "Body is required";
  }

  if (Object.keys(errors).length > 0) {
    return json(errors, { status: 400 });
  }

  // Assume createPost returns the new post object
  const newPost = await createPost({ title, body });

  // Redirect to the new post's page!
  return redirect(`/posts/${newPost.slug}`);
}

export default function NewPost() {
  // ... component remains the same ...
}

It's that simple!

  • We import redirect from @remix-run/node.
  • After the data is successfully saved and we have our newPost, we return redirect(...) with the path we want to send the user to.

Now the complete flow is:

  1. User fills out the form and submits.
  2. The action function runs on the server.
  3. It validates the data. If invalid, it returns errors to the component.
  4. If valid, it saves the data to the database.
  5. It then returns a redirect response.
  6. Remix receives this response in the browser and automatically navigates the user to the new page.

This entire flow perfectly mimics how the web has worked for decades, but Remix makes it feel fast and modern for the user. It's a truly elegant solution to a fundamental web development task.

Further Reading 📚

To dive deeper, the official Remix documentation is your best friend. It's well-written and full of great examples.

Challenge

Challenge: Implement a 'Create Post' Form in Remix

Your task is to build a complete Remix route module that allows users to create a new blog post. You will need to implement both the server-side action function for data handling and validation, and the client-side React component to render the form and display feedback.

Requirements:

  1. Server-side action Function:

    • Export an async function named action.
    • It must handle a POST request.
    • Parse the incoming form data to get the title and content fields.
    • Implement validation:
      • If the title is empty, add a title error message.
      • If the content is empty, add a content error message.
    • If there are any validation errors, return a json response containing an errors object with the messages. The response status code must be 400.
    • If the data is valid, return a redirect to the path /posts/new-post-successfully-created.
  2. Client-side Component (NewPost):

    • Render a Remix <Form> component with method="post".
    • The form must contain an <input type="text" name="title" /> and a <textarea name="content" />.
    • Include a submit <button>.
    • Use the useActionData hook to access data returned from the action function.
    • If a validation error for title exists in the action data, display it near the title input.
    • If a validation error for content exists in the action data, display it near the content textarea.

Expected result

Your final code should be a single file containing a default exported React component and a named action function.

  • The action function should correctly parse formData, validate that title and content are not empty, and return a json response with a { errors: { title: '...', content: '...' } } payload and a 400 status on failure. On success, it must return a redirect('/posts/new-post-successfully-created') response.

  • The NewPost component must render a <Form> with method="post". Inside the form, it should use the useActionData hook to access validation errors. It must conditionally display an error message for the title (e.g., actionData?.errors?.title) and an error message for the content (e.g., actionData?.errors?.content) if they exist.

jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.