Files
klatab/common/ToastProvider.tsx
2024-09-15 14:36:20 +02:00

48 lines
1.5 KiB
TypeScript

import React, { createContext, useContext, useState } from 'react';
// Defines the three kinds of message that are displayed
export enum ToastType {
Info = "INFO",
Error = "ERROR",
Success = "SUCCESS",
Warn = "WARN",
}
// Defines the parameters required to display the toast
type ToastConfigType = { type: ToastType; message: string; duration: number };
// The toast context exposes this object throughout the app
type ToastContextType = {
toastConfig: ToastConfigType | null;
showToast: (type: ToastType, message: string, duration?: number) => void;
hideToast: () => void;
};
// Creates the toast context
export const ToastContext = createContext<ToastContextType | null>(null);
export const ToastProvider = ({ children }) => {
// Calls setToastConfig in order to control the toast
// toastConfig is null by default so the toast is hidden
const [toastConfig, setToastConfig] = useState<ToastConfigType>();
function showToast(type: ToastType, message: string, duration = 0) {
// Calls setToastConfig to show the toast
setToastConfig({ type, message, duration });
}
function hideToast() {
// Sets toast config to null in order to hide the toast
setToastConfig(null);
}
return (
<ToastContext.Provider value={{ toastConfig, showToast, hideToast }}>
{children}
</ToastContext.Provider>
);
};
export function useToast() {
return useContext(ToastContext)!;
}