emilkowalski / sonner

An opinionated toast component for React.
https://sonner.emilkowal.ski
MIT License
7.69k stars 237 forks source link

Show error toast if there is error search param in url #463

Open muezz opened 2 days ago

muezz commented 2 days ago

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>
    );
    }
  2. 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.