'Redirect route and display message

I am wondering if there is a way to redirect a route or return a Response with a data and fetch it at another page with the loader function.

Basically I am trying to create a new object with a form and redirect to another page where I wanted to display a creation success message.

Here is a form page example:

I am trying to send the message in the Response body.

import { ActionFunction, Form } from "remix";

export const action: ActionFunction = async ({ request }) => {
  // const formData = await request.formData();

  return new Response(JSON.stringify({ message: "Hello world!" }), {
    status: 303,
    headers: {
      Location: "/new-page",
    },
  });
};

export default function Index() {
  return (
    <div>
      <Form method="post">
        <input type="text" id="name" name="name" />
        <button type="submit">Submit</button>
      </Form>
    </div>
  );
}

And at the NewPage I needed to know if there is a way to get the message on the redirect response.

import { ActionFunction } from "remix";

export const action: ActionFunction = async ({ request }) => {
  const formData = await request.formData();

  // Get message here

  return {
    message: "",
  };
};

export default function NewPage() {
  return <div>New Page</div>;
}


Solution 1:[1]

It's a good use case for session flash message ?

https://remix.run/docs/en/v1/api/remix#sessionflashkey-value

The documentation provides a good example, but the idea behind that is :

  • Get your form data in Index's action
  • Store the stringify data in a session cookie flash message
  • Return a response, using redirect function (helper imported from remix, that make a Response redirect for you)
  • In NewPage's loader, read the session cookie message and return it. Don't forget to commit your session, it'll delete this flash message for you
  • Use useLoaderData hook in your component to get the loader's return data
//sessions.server.ts
import { createCookieSessionStorage } from "remix";

// https://remix.run/docs/en/v1/api/remix#createcookiesessionstorage
const { getSession, commitSession, destroySession } =
  createCookieSessionStorage({
    cookie: {
      name: "__session",
      secrets: ["r3m1xr0ck5"], // should be a process.env.MY_SECRET
      sameSite: "lax",
    },
  });
import { ActionFunction, Form } from "remix";
import { getSession, commitSession } from "./sessions";

export const action: ActionFunction = async ({ request }) => {
  // const formData = await request.formData();

  session.flash("myMessageKey", "Hello world!");

  return redirect("/new-page", {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });
};

export default function Index() {
  return (
    <div>
      <Form method="post">
        <input type="text" id="name" name="name" />
        <button type="submit">Submit</button>
      </Form>
    </div>
  );
}
import { LoaderFunction } from "remix";
import { getSession, commitSession } from "./sessions";

export const loader: LoaderFunction = async ({ request }) => {
  const formData = await request.formData();

  // Get message here
  const session = await getSession(
    request.headers.get("Cookie")
  );
  const message = session.get("myMessageKey") || null;

  return json(
    { message },
    {
      headers: {
        "Set-Cookie": await commitSession(session), //will remove the flash message for you
        // "Set-Cookie": await commitSession(session, { maxAge: SESSION_MAX_AGE }), //re set max age if you previously set a max age for your sessions.
      },
    }
  );
};

export default function NewPage() {
  const { message } = useLoaderData();
  return <div>New Page {message}</div>;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1