Last active
July 22, 2020 07:42
-
-
Save MrHertal/d9fe32ef7b18a6b42fe44d2f0631d035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
// Defines the three kinds of message that are displayed | |
export enum ToastType { | |
Info = "INFO", | |
Error = "ERROR", | |
Success = "SUCCESS", | |
} | |
// 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 = React.createContext<ToastContextType | null>(null); | |
export const ToastProvider: React.FC = ({ children }) => { | |
// Calls setToastConfig in order to control the toast | |
// toastConfig is null by default so the toast is hidden | |
const [ | |
toastConfig, | |
setToastConfig, | |
] = React.useState<ToastConfigType | null>(null); | |
function showToast(type: ToastType, message: string, duration = 4000) { | |
// 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> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment