useful-custom-react-hooks
Version:
A collection of useful custom React hooks to simplify common tasks and enhance your React applications.
39 lines (38 loc) • 1.71 kB
JavaScript
import { useState, useEffect } from 'react';
export const useCookie = (key) => {
const [value, setValue] = useState('');
const getCookie = () => {
var _a;
const cookieValue = (_a = document.cookie
.split(';')
.find((i) => i.trim().split('=')[0] === key)) === null || _a === void 0 ? void 0 : _a.split('=')[1];
if (cookieValue) {
setValue(cookieValue);
}
else {
setValue('');
}
};
useEffect(() => {
getCookie();
}, []);
const setCookie = (value, opts) => {
if (value === null) {
document.cookie = `${key}=${value}; expires=${new Date(Date.now() - 1000).toUTCString()};`;
getCookie();
}
else {
const expirationDate = (opts === null || opts === void 0 ? void 0 : opts.expires)
? `expires=${opts.expires.toUTCString()};`
: '';
const sameSite = (opts === null || opts === void 0 ? void 0 : opts.sameSite) ? `SameSite=${opts.sameSite};` : '';
const secure = (opts === null || opts === void 0 ? void 0 : opts.secure) ? `Secure;` : '';
const path = (opts === null || opts === void 0 ? void 0 : opts.path) ? `path=${opts === null || opts === void 0 ? void 0 : opts.path};` : '';
const domain = (opts === null || opts === void 0 ? void 0 : opts.domain) ? `domain=${opts === null || opts === void 0 ? void 0 : opts.domain};` : '';
const cookie = `${key}=${value}; ${expirationDate} ${secure} ${sameSite} ${path} ${domain}`;
document.cookie = cookie;
getCookie();
}
};
return [value, setCookie];
};