44 lines
1.0 KiB
TypeScript
44 lines
1.0 KiB
TypeScript
|
import { Snackbar } from "@mui/material";
|
||
|
|
||
|
import React, { PropsWithChildren } from "react";
|
||
|
|
||
|
type SnackbarContext = (message: string, duration?: number) => void;
|
||
|
|
||
|
const SnackbarContextK = React.createContext<SnackbarContext | null>(null);
|
||
|
|
||
|
export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
||
|
const [open, setOpen] = React.useState(false);
|
||
|
|
||
|
const [message, setMessage] = React.useState("");
|
||
|
const [duration, setDuration] = React.useState(0);
|
||
|
|
||
|
const handleClose = () => {
|
||
|
setOpen(false);
|
||
|
};
|
||
|
|
||
|
const hook: SnackbarContext = (message, duration) => {
|
||
|
setMessage(message);
|
||
|
setDuration(duration ?? 6000);
|
||
|
setOpen(true);
|
||
|
};
|
||
|
|
||
|
return (
|
||
|
<>
|
||
|
<SnackbarContextK.Provider value={hook}>
|
||
|
{p.children}
|
||
|
</SnackbarContextK.Provider>
|
||
|
|
||
|
<Snackbar
|
||
|
open={open}
|
||
|
autoHideDuration={duration}
|
||
|
onClose={handleClose}
|
||
|
message={message}
|
||
|
/>
|
||
|
</>
|
||
|
);
|
||
|
}
|
||
|
|
||
|
export function useSnackbar(): SnackbarContext {
|
||
|
return React.useContext(SnackbarContextK)!;
|
||
|
}
|