Skip to content

Instantly share code, notes, and snippets.

@DonnieTD
Created April 23, 2021 08:00
Show Gist options
  • Save DonnieTD/fe928b1aadc4ecf01424e9ab46930e35 to your computer and use it in GitHub Desktop.
Save DonnieTD/fe928b1aadc4ecf01424e9ab46930e35 to your computer and use it in GitHub Desktop.
with Persist atom creator / with immer / with immer and persist
///////////////// CREATE ATOM THAT PERSISTS
import { atomWithReducer } from "jotai/utils";
import { WritableAtom } from "jotai/core/types";
type withpersistType = <T>(key: string, initial: T) => WritableAtom<T, T>;
const persis = (key: string, item: any) => {
localStorage.setItem(key, JSON.stringify(item));
return item;
};
export const withPersist: withpersistType = <T>(key: string, initial: T) => {
return atomWithReducer(
JSON.parse(localStorage.getItem(key) || "null") !== null
? (JSON.parse(localStorage.getItem(key) || "null") as T)
: persis(key, initial),
(_prev, newItem: T) => {
return persis(key, newItem);
}
);
};
//// Derive atom from passed atom with immer produce
import { atom } from "jotai";
import { WritableAtom } from "jotai/core/types";
import { produce, Draft } from "immer";
type withImmerType = <Value>(
anAtom: WritableAtom<Value, Value>
) => WritableAtom<Value, (draft: Draft<Value>) => void>;
export const withImmer: withImmerType = <Value>(
anAtom: WritableAtom<Value, Value>
) =>
atom(
(get) => get(anAtom),
(get, set, fn: (draft: Draft<Value>) => void) =>
set(
anAtom,
produce(get(anAtom), (draft) => fn(draft))
)
);
// Create an immutable atom that persists
import { WritableAtom } from "jotai/core/types";
import { Draft } from "immer";
import { withImmer } from "./withImmer";
import { withPersist } from "./withPersist";
type ImmerPersistType = <T>(
key: string,
initial: T
) => WritableAtom<T, (draft: Draft<T>) => void>;
export { withImmer } from "./withImmer";
export { withPersist } from "./withPersist";
export const withImmerPersist: ImmerPersistType = <T>(
key: string,
initial: T
) => withImmer<T>(withPersist<T>(key, initial));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment