跳到主要内容

useCookie

有助于在 CookieStore 中存储、更新和删除值的 hook

Usage

实时编辑器
function Demo() {
    const defaultOption = {
    path: "/",
  };
  const cookieName = "cookie-key";
  const [cookieValue, updateCookie, refreshCookie] = useCookie(
    cookieName,
    defaultOption,
    "default-value",
  );

  const updateButtonClick = () => {
    updateCookie("new-cookie-value");
  };

  const deleteButtonClick = () => {
    updateCookie(undefined);
  };

  const change = () => {
    if ("cookieStore" in window) {
      const store = window.cookieStore as any;
      store.set({ name: cookieName, value: "changed" });
    }
    else {
      document.cookie = `${cookieName}=changed; path=/`;
    }
  };

  return (
    <div>
      <p>Click on the button to update or clear the cookie</p>
      <p color="blue">cookie: {cookieValue || "no value"}</p>
      <button onClick={updateButtonClick}>Update the cookie</button>
      <button onClick={deleteButtonClick}>Clear the cookie</button>
      <button onClick={change}>
        Changing the cookie through other methods
      </button>
      <button onClick={refreshCookie}>Refresh the cookie</button>
    </div>
  );
}

结果
Loading...

API

useCookie

Returns

readonly [UseCookieState, (newValue: UseCookieState | ((prevState: UseCookieState) => UseCookieState)) => void, () => void]: 包含以下元素的元组:

  • cookie 的当前值。
  • 更新 cookie 值的函数。
  • 刷新 cookie 值的函数,以防其他事件更改它。

Arguments

参数名描述类型默认值
key键值string (必填)-
options透传给 js-cookie 的参数any-
defaultValue默认值,ssr必须传递string | undefined-

useCookieState

Type

export type UseCookieState = string | undefined;