Created
November 11, 2022 21:45
-
-
Save squarism/5a939933a907096a94d0a9ebaa0a2b80 to your computer and use it in GitHub Desktop.
How to do flash messages or notices or toasts in remix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/services/notice.server.ts | |
const { getSession, commitSession, destroySession } = | |
createCookieSessionStorage({ | |
cookie: { | |
name: "notice", | |
sameSite: "lax", | |
path: "/", | |
httpOnly: true, | |
secrets: [process.env.COOKIE_SECRET || "CHANGEME"], | |
secure: process.env.NODE_ENV === "production", | |
}, | |
}) | |
// I'm using a component which has a title and a body | |
// this is why I have message and title | |
const setNotice = async ( | |
request: Request, | |
message: string, | |
title?: string | |
): Promise<Headers> => { | |
const noticeSession = await getSession(request.headers.get("cookie")) | |
noticeSession.flash("message", message) | |
if (title) noticeSession.flash("title", title) | |
const headers = new Headers() | |
headers.append("Set-Cookie", await commitSession(noticeSession)) | |
return headers | |
} | |
export { getSession, commitSession, destroySession, setNotice } | |
// ------------------------------------------------------------------- | |
// how to set it | |
// app/routes/login.tsx | |
import { setNotice } from '~/services/notice.server' | |
// in the loader | |
// using remix-auth | |
const user = await authenticator.isAuthenticated(request) | |
if (user) { | |
const headers = await setNotice(request, "You are already logged in") | |
return redirect(`/`, { headers }) | |
} | |
// ------------------------------------------------------------------- | |
// how to read it | |
// app/routes/index.tsx or something | |
// here I'm importing the notice session server as aliases because this route | |
// also has auth in it | |
import { | |
commitSession as commitNoticeSession, | |
getSession as getNoticeSession, | |
} from "~/services/notice.server"; | |
// read the notice flash | |
const noticeSession = await getNoticeSession(request.headers.get("cookie")); | |
const flashMessage = noticeSession.get("message") | |
const flashTitle = noticeSession.get("title") | |
// you have to be sure to set the session after reading it | |
// so when you return from your loader | |
return json({ data, flashMessage, flashTitle }, { | |
headers: { | |
"Set-Cookie": await commitNoticeSession(noticeSession), | |
}, | |
}) | |
// ------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment