@mirawision/reactive-hooks
Version:
A comprehensive collection of 50+ React hooks for state management, UI interactions, device APIs, async operations, drag & drop, audio/speech, and more. Full TypeScript support with SSR safety.
66 lines (65 loc) • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useCookie = useCookie;
const react_1 = require("react");
/**
* A hook that manages state bound to a cookie.
* @param name Cookie name
* @param initial Initial value if cookie doesn't exist
* @param opts Cookie options (expiration, path, etc.)
* @returns Tuple with current value, setter, and remove function
*/
function useCookie(name, initial, opts = {}) {
const [value, setValue] = (0, react_1.useState)(() => {
if (typeof document === 'undefined')
return initial;
return getCookie(name) ?? initial;
});
// Update state when cookie changes
(0, react_1.useEffect)(() => {
setValue(getCookie(name) ?? initial);
}, [name, initial]);
const updateCookie = (0, react_1.useCallback)((newValue) => {
if (typeof document === 'undefined')
return;
if (newValue === null) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT${opts.path ? `; path=${opts.path}` : ''}`;
setValue(undefined);
}
else {
const encodedValue = encodeURIComponent(newValue);
let cookie = `${name}=${encodedValue}`;
if (opts.days) {
const date = new Date();
date.setTime(date.getTime() + opts.days * 24 * 60 * 60 * 1000);
cookie += `; expires=${date.toUTCString()}`;
}
if (opts.path)
cookie += `; path=${opts.path}`;
if (opts.sameSite)
cookie += `; samesite=${opts.sameSite}`;
if (opts.secure || opts.sameSite === 'None')
cookie += '; secure';
document.cookie = cookie;
setValue(newValue);
}
}, [name, opts]);
const removeCookie = (0, react_1.useCallback)(() => {
updateCookie(null);
}, [updateCookie]);
return [value, updateCookie, removeCookie];
}
function getCookie(name) {
if (typeof document === 'undefined')
return undefined;
const cookies = document.cookie.split(';');
const cookie = cookies.find(c => c.trim().startsWith(name + '='));
if (!cookie)
return undefined;
try {
return decodeURIComponent(cookie.trim().substring(name.length + 1));
}
catch {
return undefined;
}
}