Skip to content

Commit

Permalink
feat: sessions survive across refreshes
Browse files Browse the repository at this point in the history
  • Loading branch information
sohrab- committed Oct 3, 2022
1 parent 10e7570 commit f66cac6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
4 changes: 1 addition & 3 deletions src/hooks/useConfigStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import shallow from "zustand/shallow";
import { PersistentState } from "../types/state";
import { DEFAULT_PERSISTENT_STATE } from "../utils/state";

const LOCAL_STORAGE_KEY = "bcsol-config";

/**
* Provides access to the LocalStorage Zustand store
*/
Expand All @@ -19,7 +17,7 @@ export const useConfigStore = create<PersistentState>()(
},
}),
{
name: LOCAL_STORAGE_KEY,
name: "bcsol-config",
version: 1,
}
)
Expand Down
45 changes: 32 additions & 13 deletions src/hooks/useSessionStore.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import produce from "immer";
import create from "zustand";
import { subscribeWithSelector } from "zustand/middleware";
import { persist, subscribeWithSelector } from "zustand/middleware";
import shallow from "zustand/shallow";
import { SessionStateWithoutUndo, SessionStateWithUndo } from "../types/state";
import {
Expand All @@ -13,12 +13,25 @@ import {
/**
* Provides access to in-memory Zustand store, for state that can be undo/redo'ed
*/
export const useSessionStoreWithUndo = create<SessionStateWithUndo>((set) => ({
...DEFAULT_SESSION_STATE_WITH_UNDO,
set: (fn) => {
set(produce(fn));
},
}));
export const useSessionStoreWithUndo = create<SessionStateWithUndo>()(
persist(
(set) => ({
...DEFAULT_SESSION_STATE_WITH_UNDO,
set: (fn) => {
set(produce(fn));
},
}),
{
name: "bscol-with-undo",
getStorage: () => sessionStorage,
serialize: ({ state, ...theRest }) =>
JSON.stringify({
...theRest,
state: { ...state, lastUpdatedAt: new Date().getTime() },
}),
}
)
);

export const useShallowSessionStoreWithUndo = <U>(
selector: (state: SessionStateWithUndo) => U
Expand All @@ -28,12 +41,18 @@ export const useShallowSessionStoreWithUndo = <U>(
* Provides access to in-memory Zustand store, for state that should not be undo/redo'ed
*/
export const useSessionStoreWithoutUndo = create<SessionStateWithoutUndo>()(
subscribeWithSelector((set) => ({
...DEFAULT_SESSION_STATE_WITHOUT_UNDO,
set: (fn) => {
set(produce(fn));
},
}))
persist(
subscribeWithSelector((set) => ({
...DEFAULT_SESSION_STATE_WITHOUT_UNDO,
set: (fn) => {
set(produce(fn));
},
})),
{
name: "bscol-without-undo",
getStorage: () => sessionStorage,
}
)
);

export const useShallowSessionStoreWithoutUndo = <U>(
Expand Down

0 comments on commit f66cac6

Please sign in to comment.