-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookies-context-provider.tsx
83 lines (72 loc) · 2.13 KB
/
cookies-context-provider.tsx
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use client'
import {
PropsWithChildren,
createContext,
useCallback,
useEffect,
useState,
} from 'react'
import Cookies from 'js-cookie'
export const CookiesContext = createContext({
cookiesAccepted: false,
setCookiesAccepted: (accepted: boolean) => {},
trackingCookiesAccepted: false,
setTrackingCookiesAccepted: (accepted: boolean) => {},
popupOpen: false,
openPopup: () => {},
closePopup: () => {},
})
export const CookiesContextProvider = ({ children }: PropsWithChildren<{}>) => {
const [cookiesAccepted, setCookiesAcceptedStorage] = useState<boolean>(false)
const [popupOpen, setPopupOpenStorage] = useState<boolean>(false)
const [trackingCookiesAccepted, setTrackingCookiesAcceptedStorage] =
useState<boolean>(false)
useEffect(() => {
const accepted = Cookies.get('accepted-cookies') || false
setCookiesAcceptedStorage(!!accepted)
}, [setCookiesAcceptedStorage])
useEffect(() => {
const accepted = Cookies.get('accepted-tracking-cookies') || false
setTrackingCookiesAcceptedStorage(!!accepted)
}, [setTrackingCookiesAcceptedStorage])
const setCookiesAccepted = useCallback(
(accepted: boolean) => {
Cookies.set('accepted-cookies', accepted.toString(), {
expires: 30,
})
setCookiesAcceptedStorage(accepted)
},
[setCookiesAcceptedStorage],
)
const setTrackingCookiesAccepted = useCallback(
(accepted: boolean) => {
Cookies.set('accepted-tracking-cookies', accepted.toString(), {
expires: 30,
})
setTrackingCookiesAcceptedStorage(accepted)
},
[setTrackingCookiesAcceptedStorage],
)
const openPopup = useCallback(() => {
setPopupOpenStorage(true)
}, [setPopupOpenStorage])
const closePopup = useCallback(() => {
setPopupOpenStorage(false)
}, [setPopupOpenStorage])
return (
<CookiesContext.Provider
value={{
cookiesAccepted,
setCookiesAccepted,
trackingCookiesAccepted,
setTrackingCookiesAccepted,
popupOpen,
openPopup,
closePopup,
}}
>
{children}
</CookiesContext.Provider>
)
}
export default CookiesContextProvider