sonner
sonner copied to clipboard
Show error toast if there is error search param in url
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 🔁:
- 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>
);
}
- In the
ErrorTest
component, using theuseEffect
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.