Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Created October 20, 2022 21:47
Show Gist options
  • Save sergiodxa/3a63f20aa04355bb1e177e17af9d9db3 to your computer and use it in GitHub Desktop.
Save sergiodxa/3a63f20aa04355bb1e177e17af9d9db3 to your computer and use it in GitHub Desktop.
An article completely generated by GitHub Copilot based on a title, with just a few minor errors

Persist user inputs after form submit in Remix

This tutorial will show you how to persist user inputs after form submit in Remix.

Prerequisites

Steps

  1. Create a new app with remix new and select the app template
  2. Open app/routes/index.tsx and replace the content with the following:
import { Link, Outlet, useLocation } from "react-router-dom";
import { useQuery } from "remix";
import { Meta, Links, Scripts, LiveReload } from "remix";
import { Form, useActionData, useCatch } from "remix";
import { json } from "remix-utils";

export function meta() {
  return {
    title: "Remix App",
    description: "Welcome to Remix!",
  };
}

export function links() {
  return [
    { rel: "stylesheet", href: "app.css" },
    { rel: "icon", href: "favicon.ico" },
  ];
}

export function scripts() {
  return [{ src: "app.js" }];
}
  1. Add a form to the index.tsx file:
export default function Index() {
  const location = useLocation();
  const query = new URLSearchParams(location.search);
  const name = query.get("name") || "";

  return (
    <div>
      <h1>Hello {name}!</h1>
      <form method="post">
        <label htmlFor="name">Name</label>
        <input id="name" name="name" type="text" defaultValue={name} />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}
  1. Add a post handler to the index.tsx file:
export function action({ request }: { request: Request }) {
  const form = new URLSearchParams(await request.text());
  const name = form.get("name") || "";

  return json({ name }, { status: 303, headers: { location: `/?name=${name}` } });
}
  1. Run remix dev and open http://localhost:3000 in your browser

Learn more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment