UNPKG

@vue-widget/hooks

Version:

hooks from react to vue

31 lines (30 loc) 1.25 kB
import { __assign, __rest } from "tslib"; import Cookies from "js-cookie"; import { useMemoizedFn } from "../useMemoizedFn"; import { isFunction, isString } from "../utils"; import { useState } from "../useState"; export function useCookieState(cookieKey, options) { if (options === void 0) { options = {}; } var _a = useState(function () { var cookieValue = Cookies.get(cookieKey); if (isString(cookieValue)) return cookieValue; if (isFunction(options.defaultValue)) { return options.defaultValue(); } return options.defaultValue; }), state = _a[0], setState = _a[1]; var updateState = useMemoizedFn(function (newValue, newOptions) { if (newOptions === void 0) { newOptions = {}; } var _a = __assign(__assign({}, options), newOptions), _b = _a.defaultValue, defaultValue = _b === void 0 ? {} : _b, restOptions = __rest(_a, ["defaultValue"]); var value = isFunction(newValue) ? newValue(state.value) : newValue; setState(value); if (value === undefined) { Cookies.remove(cookieKey); } else { Cookies.set(cookieKey, value, restOptions); } }); return [state, updateState]; }