LFFE-12 create toast and useToast
This commit is contained in:
37
src/lib/app/contexts/toast.jsx
Normal file
37
src/lib/app/contexts/toast.jsx
Normal file
@@ -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 (
|
||||
<ToastContext.Provider value={{state, dispatch}}>
|
||||
{children}
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
};
|
||||
21
src/lib/app/hooks/useToast.jsx
Normal file
21
src/lib/app/hooks/useToast.jsx
Normal file
@@ -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;
|
||||
Reference in New Issue
Block a user