Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compatibility with localForage #55

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 56 additions & 52 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { AtomEffect } from 'recoil'

type PersistItemValue = string | undefined | null

export interface PersistStorage {
setItem(key: string, value: string): void | Promise<void>
mergeItem?(key: string, value: string): Promise<void>
getItem(key: string): null | string | Promise<string>
setItem(key: string, value: string): any
mergeItem?(key: string, value: string): any
getItem(key: string): PersistItemValue | Promise<PersistItemValue>
}

export interface PersistState {}

export interface PersistConfiguration {
key?: string
storage?: PersistStorage
key: string
storage: PersistStorage
}

interface PendingChanges {
queue: Promise<any> | null
updates: Partial<PersistState>
reset: Record<string, boolean>
}

/**
Expand All @@ -19,84 +29,78 @@ export interface PersistConfiguration {
* @param config.storage Local storage to use, defaults to `localStorage`
*/
export const recoilPersist = (
config: PersistConfiguration = {},
config: Partial<PersistConfiguration> = {},
): { persistAtom: AtomEffect<any> } => {
if (typeof window === 'undefined') {
return {
persistAtom: () => {},
}
}

const { key = 'recoil-persist', storage = localStorage } = config
const {
key = 'recoil-persist' as PersistConfiguration['key'],
storage = localStorage as PersistConfiguration['storage'],
} = config

const pendingChanges: PendingChanges = {
queue: null,
updates: {},
reset: {},
}

const persistAtom: AtomEffect<any> = ({ onSet, node, trigger, setSelf }) => {
if (trigger === 'get') {
const state = getState()
if (typeof state.then === 'function') {
state.then((s) => {
if (s.hasOwnProperty(node.key)) {
setSelf(s[node.key])
}
})
}
if (state.hasOwnProperty(node.key)) {
setSelf(state[node.key])
}
getState().then((s) => {
if (s.hasOwnProperty(node.key)) {
setSelf(s[node.key])
}
})
}

onSet(async (newValue, _, isReset) => {
const state = getState()
if (typeof state.then === 'function') {
state.then((s: any) => updateState(newValue, s, node.key, isReset))
onSet((newValue, _, isReset) => {
if (isReset) {
pendingChanges.reset[node.key] = true
delete pendingChanges.updates[node.key]
} else {
updateState(newValue, state, node.key, isReset)
pendingChanges.updates[node.key] = newValue
}
if (!pendingChanges.queue) {
pendingChanges.queue = getState().then((state) => {
updateState(state, pendingChanges)
pendingChanges.queue = null
pendingChanges.reset = {}
pendingChanges.updates = {}
})
}
})
}

const updateState = (
newValue: any,
state: any,
key: string,
isReset: boolean,
) => {
if (isReset) {
const updateState = (state: PersistState, changes: PendingChanges) => {
Object.keys(changes.reset).forEach((key) => {
delete state[key]
} else {
state[key] = newValue
}

})
Object.keys(changes.updates).forEach((key) => {
state[key] = changes.updates[key]
})
setState(state)
}

const getState = (): any => {
const toParse = storage.getItem(key)
const parseState = (toParse: PersistItemValue): PersistState => {
if (toParse === null || toParse === undefined) {
return {}
}
if (typeof toParse === 'string') {
return parseState(toParse)
}
if (typeof toParse.then === 'function') {
return toParse.then(parseState)
}

return {}
}

const parseState = (state: string) => {
if (state === undefined) {
return {}
}
try {
return JSON.parse(state)
return JSON.parse(toParse)
} catch (e) {
console.error(e)
return {}
}
}

const setState = (state: any): void => {
const getState = (): Promise<PersistState> =>
Promise.resolve(storage.getItem(key)).then(parseState)

const setState = (state: PersistState): void => {
try {
if (typeof storage.mergeItem === 'function') {
storage.mergeItem(key, JSON.stringify(state))
Expand Down
7 changes: 4 additions & 3 deletions test/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const asyncStorage = (): TestableStorage => {
setItem: (key: string, value: string) => {
return new Promise((resolve) => {
s[key] = value
resolve()
resolve(undefined)
})
},
getItem: (key: string): Promise<string> => {
Expand Down Expand Up @@ -103,7 +103,8 @@ function testPersistWith(storage: TestableStorage) {
const updateMultiple = useRecoilCallback(({ set }) => () => {
set(counterState, 10)
set(counterFamily('2'), 10)
})
}, []);

return (
<div>
<p data-testid="count-value">{count}</p>
Expand Down Expand Up @@ -382,7 +383,7 @@ function testPersistWith(storage: TestableStorage) {
)
})

it.skip('should handle updating multiple atomes', async () => {
it('should handle updating multiple atoms', async () => {
const { getByTestId } = render(
<RecoilRoot>
<Demo />
Expand Down