I've been playing with MUI React library and found Snackbar.
I found it a nice idea for displaying feedback information for a user. In my app I'd like use it to display results of sending a request to server (e.g. "data sent successfully", etc).
I used the code defined here, but I quickly realized that in order to display messages dynamically I need to store message text, isOpen
boolean and message type (success
, error
, etc.) with useState
and then set it before showing a message, e.g.
const sendData = () => {
fetch({
// ...
})
.then(() => {
setMessage("Success!");
setLevel("success");
setOpen(true);
})
.catch((err) => {
setMessage("Failed to send request.");
setLevel("error");
setOpen(true);
});
}
1.) This is inconvenient. I wonder if there's a way to use it in a simpler way, like this:
const sendData = () => {
fetch({
// ...
})
.then(() => {
showMessage("Success!", "success");
})
.catch((err) => {
setMessage("Failed to send request.", "error");
});
}
2.) The Snackbar
component defined like this is local to its parent component. I wonder if it's possible to make it reusable and share it throughout my application.
I agree, We need to create a lot of unnecessary states to show Snackbar
. You can use an alternative and simple solution to this. It is a library built on top of MUI Snackbar. As you check at MUI docs, MUI adds it to complementary projects on the Snackbar documentation page.
It is a very easy-to-use and highly customizable Snackbar hook
. You add <SnackbarProvider/>
once on the top level of your app and then you can access it anywhere using useSnackbar()
hook.
You can find more examples and docs on their official page.
I hope it helps.