forked from Selleo/ReactNativeSimpleToastExample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToastContext.js
50 lines (43 loc) · 941 Bytes
/
ToastContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import React, {
createContext,
useState,
useEffect,
useRef,
useCallback,
} from 'react';
const initialToast = {
message: '',
type: null,
visible: false,
};
export const ToastContext = createContext({});
export const ToastProvider = ({children}) => {
const [toast, setToast] = useState(initialToast);
const timeout = useRef();
const show = useCallback(args => {
setToast({...initialToast, visible: true, ...args});
}, []);
const hide = useCallback(() => {
setToast({...toast, visible: false});
}, [toast]);
useEffect(() => {
if (toast.visible) {
timeout.current = setTimeout(hide, 1500);
return () => {
if (timeout.current) {
clearTimeout(timeout.current);
}
};
}
}, [hide, toast]);
return (
<ToastContext.Provider
value={{
hide,
show,
toast,
}}>
{children}
</ToastContext.Provider>
);
};