ahooks
Version:
react hooks library
32 lines (31 loc) • 1.19 kB
JavaScript
import { __rest } from "tslib";
import Cookies from 'js-cookie';
import { useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { isFunction, isString } from '../utils';
const useCookieState = (cookieKey, options = {}) => {
const [state, setState] = useState(() => {
const cookieValue = Cookies.get(cookieKey);
if (isString(cookieValue)) {
return cookieValue;
}
if (isFunction(options.defaultValue)) {
return options.defaultValue();
}
return options.defaultValue;
});
const updateState = useMemoizedFn((newValue, newOptions = {}) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _a = Object.assign(Object.assign({}, options), newOptions), { defaultValue } = _a, restOptions = __rest(_a, ["defaultValue"]);
const value = isFunction(newValue) ? newValue(state) : newValue;
setState(value);
if (value === undefined) {
Cookies.remove(cookieKey);
}
else {
Cookies.set(cookieKey, value, restOptions);
}
});
return [state, updateState];
};
export default useCookieState;