LoginSignup
30
14

More than 1 year has passed since last update.

Next.jsでRecoilの永続化

Posted at

ログイン認証済みかどうかの判別をRecoilに保存し永続化したときのメモ

永続化はRecoil-persistライブラリを使う

もともとインストールしていたRecoilのバージョンがv0.6.1でしたが、recoil-persistをインストールするとエラーとなってしまったので、バージョンをv0.5.2でインストールし直したらいけました。

npm install recoil@0.5.2 
npm install recoil-persist

RecoilRootでwrapする場所

Recoilを利用する場合はRecoilRootで全体をwrapします。
Next.jsの場合は‗app.tsxで囲えば大丈夫です。

RecoilRoot.png

Atomを設定する

続いてAtomを用意します。今回認証済みかどうかはbooleanで判定します。

import { atom } from "recoil";

export const isAuthenticatedState = atom({
	key: "isAuthenticatedState",
	default: false
});

Sessionに保存

永続化する場合は下記のコードを追加します。通常recoilPersist();とすると値はlocalStrageに保存されます。
今回はSessionStrageに保存してみようと思います。その場合recoilPersist();の引数に下記のようなオブジェクトを渡します。

import { atom } from "recoil";
import { recoilPersist } from "recoil-persist"; //追加

const { persistAtom } = recoilPersist({ //追加
	key: "recoil-persist",
	storage: sessionStorage
});

export const isAuthenticatedState = atom({
	key: "isAuthenticatedState",
	default: false,
	effects_UNSTABLE: [persistAtom] //追加
});

エラーになる

サーバーサイドエラー.png

Next .jsだとサーバー側でレンダリングを行うのでこのように怒られるようです。
サーバー側でstorageないですよって言われてしまいます。
調べたら参考になる記事がありました。

Next.js使用時にrecoil-persistのStorageを変更する

記事に習いコードを修正します。

import { atom } from "recoil";
import { recoilPersist } from "recoil-persist";

const { persistAtom } = recoilPersist({
	key: "recoil-persist",
	storage: typeof window === "undefined" ? undefined : sessionStorage //修正
});

export const isAuthenticatedState = atom({
	key: "isAuthenticatedState",
	default: false,
	effects_UNSTABLE: [persistAtom]
});

保存できてます。

セッションstorage.png

感想

いくつか詰まりましたが、とはいえRecoilでの永続化すごく簡単ですね。
recoil-persistインストールできなかったときは焦りましたが。。。

30
14
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
30
14