Skip to content

Commit

Permalink
feat: add persist middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
AnatoleLucet committed Nov 5, 2020
1 parent c1c19bf commit 4a68461
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {
State,
GetState,
SetState,
StoreApi,
PartialState,
SetState,
State,
StateCreator,
StoreApi,
} from './vanilla'

export const redux = <S extends State, A extends { type: unknown }>(
Expand Down Expand Up @@ -116,3 +116,35 @@ export const combine = <
api as StoreApi<PrimaryState>
)
)

type StateStorage = {
getItem: (key: string) => string | null | Promise<string | null>
setItem: (key: string, value: string) => void | Promise<void>
}

export const persist = <S extends State>(
name: string,
config: StateCreator<S>,
storage: StateStorage = localStorage
) => (set: SetState<S>, get: GetState<S>, api: StoreApi<S>): S => {
const state = config(
(payload) => {
set(payload)

storage.setItem(name, JSON.stringify(get()))
},
get,
api
)

;(async () => {
try {
const storedState = await storage.getItem(name)
if (storedState) set(JSON.parse(storedState))
} catch (e) {
console.error(new Error(`Unable to get to stored state in "${name}"`))
}
})()

return state
}

0 comments on commit 4a68461

Please sign in to comment.