74 lines
1.7 KiB
TypeScript
74 lines
1.7 KiB
TypeScript
import React, { createContext, useContext, useState, ReactNode } from "react";
|
|
import CustomSnackbar from "../components/common/CustomSnackbar";
|
|
|
|
interface SnackbarContextProps {
|
|
showSnackbar: (message: string, type: "success" | "error") => void;
|
|
}
|
|
|
|
const SnackbarContext = createContext<SnackbarContextProps | undefined>(
|
|
undefined
|
|
);
|
|
|
|
export const useSnackbar = () => {
|
|
const context = useContext(SnackbarContext);
|
|
if (!context) {
|
|
throw new Error("useSnackbar must be used within a SnackbarProvider");
|
|
}
|
|
return context;
|
|
};
|
|
|
|
interface SnackbarProviderProps {
|
|
children: ReactNode;
|
|
}
|
|
|
|
export const SnackbarProvider: React.FC<SnackbarProviderProps> = ({
|
|
children,
|
|
}) => {
|
|
const [snackbar, setSnackbar] = useState({
|
|
message: "",
|
|
bgColor: "",
|
|
textColor: "",
|
|
duration: 2,
|
|
visible: false,
|
|
});
|
|
|
|
const showSnackbar = (
|
|
message: string,
|
|
type: "success" | "error" | "info"
|
|
) => {
|
|
const bgColor =
|
|
type === "success" ? "#DFF2E9" : type === "error" ? "#FDEDED" : "#E0F7FA";
|
|
const textColor =
|
|
type === "success" ? "#242C3B" : type === "error" ? "#D51D10" : "#00796B";
|
|
setSnackbar({
|
|
message,
|
|
bgColor,
|
|
textColor,
|
|
duration: 2,
|
|
visible: true,
|
|
});
|
|
};
|
|
|
|
const hideSnackbar = () => {
|
|
setSnackbar((prevSnackbar) => ({
|
|
...prevSnackbar,
|
|
visible: false,
|
|
}));
|
|
};
|
|
|
|
return (
|
|
<SnackbarContext.Provider value={{ showSnackbar }}>
|
|
{children}
|
|
<CustomSnackbar
|
|
message={snackbar.message}
|
|
bgColor={snackbar.bgColor}
|
|
textColor={snackbar.textColor}
|
|
duration={snackbar.duration}
|
|
visible={snackbar.visible}
|
|
onDismiss={hideSnackbar}
|
|
/>
|
|
</SnackbarContext.Provider>
|
|
);
|
|
};
|
|
export default SnackbarProvider;
|