Sonner Toast
User always feel not comfortable when they see a blank page when they request something to backend. That's when toast come in. It give user a feedback that their request has been sent to backend. It also give user a feedback that their request has been success or failed.
This tutorial use Sonner (opens in a new tab) by https://github.com/emilkowalski (opens in a new tab).
Installing
npm install sonner
Usage
Add <Toaster />
in your _app.tsx
or _app.js
file besides <Component {...pageProps} />
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} /> <Toaster richColors closeButton />
</>
);
}
There are several types
of toast that you can use based on your need. Personally, i use success
and error
that you can take a look at Types (opens in a new tab).
richColors
is a prop that you can use to give the toast a color based on its type. closeButton
is a prop that you can use to show close button in toast.
this is just optional, you can use it or not.
Success
I use this toast when user successfully request something to backend.
toast.success("Event has been created");
Error
I use this toast when user failed request something to backend.
toast.error("Event has not been created");
Example
One example i use with this toast is when user create an event. If the event has been created, i will show success toast. If the event has not been created, i will show error toast like this:
async function handleAddSomething() {
const options = {
YOUR_OPTION_FOR_POST
};
axios
.post("YOUR_API", options)
.then((postFileReq) => {
onSuccess();
setLoading(false);
toast.success("Event has been created");
})
.catch((error) => {
const err = error as AxiosError;
if (err.response?.status === 400) {
toast.error("Event has not been created");
} else {
toast.error("Event has not been created");
}
setLoading(false);
});
}
Finish
After you finish all the step above you are all set! Toast will show up when you create a new request.