-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCookie.ts
62 lines (53 loc) · 1.74 KB
/
useCookie.ts
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
import { useCallback, useEffect, useState } from 'react';
function useCookie(key: string, initialValue: string): [string, any, any] {
// Cookie okuma islemi
// Eger daha once ayni isimle tanimlanmis cookie varsa degeri donuluyor
// Yoksa initialValue olarak gonderilen deger donduruluyor.
const readCookie = useCallback((): string => {
let name = key + '=';
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
// Ayni isimli cookie bulunduysa degerini don.
return c.substring(name.length, c.length);
}
}
// Ayni isimli cookie bulunamadiysa baslangic degerini don.
return initialValue;
}, [key, initialValue]);
// Cookie tutmak icin kullanilan state
const [cookieState, setCookieState] = useState<string>(readCookie);
// Cookie'yi kayit islemi
const setCookie = useCallback(
(value: string, maxAgeInDays: number): void => {
// Yeni cookie browser'a kaydediliyor
document.cookie = `${key}=${value}; max-age=${
60 * 60 * 24 * maxAgeInDays
}`;
// Yeni deger state'e ekleniyor
setCookieState(value);
},
[key]
);
// Cookie silme islemi
const deleteCookie = (): void => {
// Token cookie'si siliniyor
document.cookie = `${key}=; max-age=-99999999;`;
// Cookie state'i temizleniyor.
setCookieState('');
};
// Ilk cagirmada cookie okunuyor.
useEffect(() => {
setCookieState(readCookie());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Cookie State, setCookie ve deleteCookie methodlari donuluyor
return [cookieState, setCookie, deleteCookie];
}
// Hook export ediliyor
export default useCookie;