diff --git a/src/lib/app/contexts/toast.jsx b/src/lib/app/contexts/toast.jsx new file mode 100644 index 0000000..b9d4cbc --- /dev/null +++ b/src/lib/app/contexts/toast.jsx @@ -0,0 +1,37 @@ +import {createContext, useReducer} from "react"; +import {toast} from "react-toastify"; + +export const ToastContext = createContext() + +const reducer = (state, action) => { + switch (action.type) { + case "PUSH": + return { + ...state, + [action.toast_type]: [...state[action.toast_type], action.toast_id] + }; + case "DISMISS": + action.toast_type.map((item) => { + state[item].map((id) => { + toast.dismiss(id); + }) + state[item] = [] + }); + return state; + } +}; + +export const ToastProvider = ({children}) => { + const [state, dispatch] = useReducer(reducer, { + pending: [], + error: [], + warning: [], + success: [] + }); + + return ( + + {children} + + ); +}; diff --git a/src/lib/app/hooks/useToast.jsx b/src/lib/app/hooks/useToast.jsx new file mode 100644 index 0000000..5e1d5b4 --- /dev/null +++ b/src/lib/app/hooks/useToast.jsx @@ -0,0 +1,21 @@ +import {useContext} from "react"; +import {ToastContext} from "@/lib/app/contexts/toast"; + +const useToast = () => { + const {dispatch} = useContext(ToastContext); + + const pushToastList = (toast_type, toast_id) => { + dispatch({type: "PUSH", toast_type, toast_id}); + }; + + const dismissToastList = (toast_type) => { + dispatch({type: "DISMISS", toast_type}); + }; + + return { + pushToastList, + dismissToastList + } +}; + +export default useToast; \ No newline at end of file