Skip to content

Commit

Permalink
feat(store): add local storage adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
neurosnap committed Dec 18, 2023
1 parent 1e24f21 commit fb0b016
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions store/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,30 @@ export interface PersistProps<S extends AnyState> {
rehydrate: () => Operation<Result<unknown>>;
}

export function createLocalStorageAdapter<S extends AnyState>(): PersistAdapter<
S
> {
return {
getItem: function* (key: string) {
const storage = localStorage.getItem(key) || "{}";
return Ok(JSON.parse(storage));
},
setItem: function* (key: string, s: Partial<S>) {
const state = JSON.stringify(s);
try {
localStorage.setItem(key, state);
} catch (err: any) {
return Err(err);
}
return Ok(undefined);
},
removeItem: function* (key: string) {
localStorage.removeItem(key);
return Ok(undefined);
},
};
}

export function shallowReconciler<S extends AnyState>(
original: S,
persisted: Partial<S>,
Expand Down

0 comments on commit fb0b016

Please sign in to comment.