This repository was archived by the owner on Dec 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCookie.js
50 lines (40 loc) · 1.43 KB
/
useCookie.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 { useState, useEffect } from 'react';
// a custom hook to use set cookies in ypur browser
// set cookies
const setCookie = (name, value, days, path) => {
// a distant expirey date
const expires = new Date(Date.now() + days * 864e5).toUTCString();
// encodeURIComponent - Encodes a text string as a valid component of a Uniform Resource Identifier (URI).
document.cookie = `${name}=${encodeURIComponent(
value
)}; expires=${expires}; path=${path}`;
};
// get a cookie
const getCookie = (name) =>
document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=');
// Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).
return parts[0] === name ? decodeURIComponent(parts[1]) : r;
}, '');
// function to triggeer get cookie
const useCookie = (cookieName, initialValue) => {
const [cookieValue, setCookieValue] = useState(
() => getCookie(cookieName) || initialValue
);
// for saving the cookie at the very first instance
useEffect(() => {
setCookie(cookieName, cookieValue, 365, '/');
}, []);
// update cookie
const updateCookie = (value, days = 365, path = '/') => {
setCookieValue(value);
setCookie(cookieName, value, days, path);
};
// delete cookie
const deleteCookie = (path = '/') => {
updateCookie('', -1, path);
setCookieValue(null);
};
return [cookieValue, updateCookie, deleteCookie];
};
export default useCookie;