sonner icon indicating copy to clipboard operation
sonner copied to clipboard

Show error toast if there is error search param in url

Open muezz opened this issue 7 months ago • 0 comments

Describe the feature / bug 📝:

I would like to redirect the user from APIs or server actions to the same url the user came from but with an error search param. The goal is for a client component in the root layout.ts to check for that search param. And if it exists, the toast should be shown. After that, the search param should be removed from the url.

Steps to reproduce the bug 🔁:

  1. Initialize the toaster like so:
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        {children}
        <ErrorTest />
        <Toaster />
      </body>
    </html>
  );
}
  1. In the ErrorTest component, using the useEffect hook, trigger the toast animation like this:
const ErrorTest = () => {
  const searchParams = useSearchParams();
  useEffect(() => {
    const error = searchParams.get("error");
    if (!error) return;
    console.log(error);
    // alert("hello");
    toast("Something went wrong");
  }, [searchParams]);
  return null;
};

export default ErrorTest;

With this approach, I do not get any toast animation. Notice the alert dialog that is commented out. If I include that, I do get it on page load. I am not sure what it is that I am doing incorrectly.

muezz avatar Jul 01 '24 11:07 muezz