0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】zustandのpersistで独自のstorageを使用したい

Posted at

概要

状態管理のライブラリzustandでは、Persisting store dataのドキュメントにある通り、状態の値を永続化する機能があります。標準だとlocalStorage、sessionStorageが用意されているようですが、cookieなど他のstorageを使用したい場合はどうすればよいかのメモ書きです。

前提

  • 使用したzustandのバージョンは4.5.5です。

対応方針

Is it possible to use cookies for as a persist storage?のdiscussionsにある通り、別途StateStorageのinterfaceの実装を用意して、それを設定することで実現できます。

実装サンプル

上記の記事と同様に、cookieで実装する場合のサンプルは以下の通りです。

import { getCookie, setCookie, removeCookie } from "typescript-cookie";
import { create } from "zustand";
import { createJSONStorage, persist, StateStorage } from "zustand/middleware";

const cookiesStorage: StateStorage = {
  getItem: (name: string) => {
    return getCookie(name) ?? null;
  },
  setItem: (name: string, value: string) => {
    setCookie(name, value, { expires: 1 });
  },
  removeItem: (name: string) => {
    removeCookie(name);
  },
};

type SampleTokenType = {
  sampleToken: string | undefined;
  updateSampleToken: (token: string) => void;
  removeSampleToken: () => void;
};

export const useSampleTokenStore = create(
  persist<SampleTokenType>(
    (set) => ({
      sampleToken: undefined,
      updateSampleToken: (token) => set({ sampleToken: token }),
      removeSampleToken: () => set({ sampleToken: undefined }),
    }),
    {
      name: "test-storage",
      storage: createJSONStorage(() => cookiesStorage),
    }
  )
);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?