Next.js Discord

Discord Forum

Re-fetch data on server-action execution?

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hi, I have this server function:

"use server";

import { headers } from "next/headers";

/**
 * Get toast cookie data from the x-toast-data header
 * Needs the middleware.ts
 */
export async function getToastCookie() {
  "use server";
  const headerList = headers();

  const toastHeader = headerList.get("x-toast-data");

  if (!toastHeader) return null;

  try {
    const jsonData = JSON.parse(toastHeader);

    if (!jsonData.message) return null;

    if (!jsonData.variant) jsonData.variant = "info";

    return jsonData as {
      message: string;
      variant: "success" | "info" | "warning" | "error";
    };
  } catch (err) {
    console.error(err);
    return null;
  }
}


which gets called inside layout.tsx, and the response value gets passed to a component.

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const toastCookie = await getToastCookie();

  return (
    <html lang="en">
      <body
        className={cn(
          "min-h-screen, bg-background, font-sans antialiased",
          fontSans.variable,
        )}
      >
        <Navbar />
        {children}
        <CookieToaster toast={toastCookie} />
      </body>
    </html>
  );
}


I also have a middleware.ts file that turns the toast cookie into the x-toast-data header, and removes the cookie.

When running a server action that sets the toast cookie, I'd like for the getToastCookie function to re-run, and update the CookieToaster component's prop, however, it doesn't.

I've tried adding revalidatePath("/", "layout"); after setting the cookie, but that shows the cookie from the previous submission, instead of the one set just above that line.

How would I go about accomplishing that?

0 Replies