vue-hooks-plus
Version:
Vue hooks library
33 lines (32 loc) • 1.02 kB
JavaScript
import Cookies from "js-cookie";
import { ref, readonly } from "vue";
import { isFunction } from "../utils/isFunction";
function useCookieState(cookieKey, options = {}) {
const defaultValue = () => {
const cookieValue = Cookies.get(cookieKey);
if (typeof cookieValue === "string")
return cookieValue;
if (isFunction(options.defaultValue)) {
return options.defaultValue();
}
return options.defaultValue;
};
const state = ref(defaultValue());
const updateState = (newValue, newOptions = {}) => {
const { defaultValue: defaultValue2, ...restOptions } = { ...options, ...newOptions };
const getValue = () => {
const value = isFunction(newValue) ? newValue(state.value) : newValue;
if (value === void 0) {
Cookies.remove(cookieKey);
} else {
Cookies.set(cookieKey, value, restOptions);
}
return value;
};
state.value = getValue();
};
return [readonly(state), updateState];
}
export {
useCookieState as default
};