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

Fix bugs and add tests for sync storage #1

Closed
Closed
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
83 changes: 46 additions & 37 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,60 +274,69 @@ export const persist = <S extends State>(
}
}
}
// rehydrate initial state with existing stored state

let stateFromStorage
// rehydrate initial state with existing stored state
;(() => {
const postRehydrationCallback = onRehydrateStorage?.(get()) || undefined

let storageValuePending = makeThenable(storage.getItem(name))
storageValuePending
.then((storageValue) => {
if (storageValue) {
return makeThenable(deserialize(storageValue))
} else {
return makeThenable(null)
}
})
.then((deserializedStorageValue) => {
if (deserializedStorageValue) {
if (deserializedStorageValue.version !== version) {
return makeThenable(
migrate?.(
try {
let storageValuePending = makeThenable(storage.getItem(name))
storageValuePending
.then((storageValue) => {
if (storageValue) {
return makeThenable(deserialize(storageValue))
} else {
return makeThenable(null)
}
})
.then((deserializedStorageValue) => {
if (deserializedStorageValue) {
if (deserializedStorageValue.version !== version) {
stateFromStorage = migrate?.(
deserializedStorageValue.state,
deserializedStorageValue.version
)
)

return makeThenable(stateFromStorage)
} else {
stateFromStorage = deserializedStorageValue.state
set(stateFromStorage)
return makeThenable(null)
}
} else {
set(deserializedStorageValue.state)
return makeThenable(null)
}
} else {
return makeThenable(null)
}
})
.then((migratedState) => {
if (migratedState) {
set(migratedState)
return makeThenable(setItem())
} else {
})
.then((migratedState) => {
if (migratedState) {
set(migratedState)
return makeThenable(setItem())
} else {
return makeThenable(null)
}
})
.then(() => {
postRehydrationCallback?.(get(), undefined)
return makeThenable(null)
}
})
.then(() => {
postRehydrationCallback?.(get(), undefined)
return makeThenable(null)
})
// this handler will only catch promise related errors
.catch((e) => {
postRehydrationCallback?.(undefined, e)
})
})
// this handler will only catch promise related errors
.catch((e) => {
postRehydrationCallback?.(undefined, e)
})
} catch (e) {
postRehydrationCallback?.(undefined, e)
}
})()

return config(
const configRes = config(
(...args) => {
set(...args)
void setItem()
},
get,
api
)
const mergedRes = { ...configRes, ...(stateFromStorage || {}) }
return mergedRes
}
173 changes: 173 additions & 0 deletions tests/persistSync.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import create from '../src/index'
import { persist } from '../src/middleware'

const consoleError = console.error
afterEach(() => {
console.error = consoleError
})

it('can rehydrate state', () => {
let postRehydrationCallbackCallCount = 0

const storage = {
getItem: (name: string) =>
JSON.stringify({
state: { count: 42, name },
version: 0,
}),
setItem: () => {},
}

const useStore = create(
persist(
() => ({
count: 0,
name: 'empty',
}),
{
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => (state, error) => {
postRehydrationCallbackCallCount++
expect(error).toBeUndefined()
expect(state?.count).toBe(42)
expect(state?.name).toBe('test-storage')
},
}
)
)

expect(useStore.getState()).toEqual({ count: 42, name: 'test-storage' })
expect(postRehydrationCallbackCallCount).toBe(1)
})

it('can throw rehydrate error', () => {
let postRehydrationCallbackCallCount = 0

const storage = {
getItem: () => {
throw new Error('getItem error')
},
setItem: () => {},
}

create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => (_, e) => {
postRehydrationCallbackCallCount++
expect(e?.message).toBe('getItem error')
},
})
)

expect(postRehydrationCallbackCallCount).toBe(1)
})

it('can persist state', () => {
let setItemCallCount = 0

const storage = {
getItem: () => null,
setItem: (name: string, value: string) => {
setItemCallCount++
expect(name).toBe('test-storage')
expect(value).toBe(
JSON.stringify({
state: { count: 42 },
version: 0,
})
)
},
}

const useStore = create<any>(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
onRehydrateStorage: () => (_, error) => {
expect(error).toBeUndefined()
},
})
)

expect(useStore.getState()).toEqual({ count: 0 })
useStore.setState({ count: 42 })
expect(useStore.getState()).toEqual({ count: 42 })
expect(setItemCallCount).toBe(1)
})

it('can migrate persisted state', () => {
let migrateCallCount = 0
let setItemCallCount = 0

const storage = {
getItem: () =>
JSON.stringify({
state: { count: 42 },
version: 12,
}),
setItem: (_: string, value: string) => {
setItemCallCount++
expect(value).toBe(
JSON.stringify({
state: { count: 99 },
version: 13,
})
)
},
}

const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
getStorage: () => storage,
onRehydrateStorage: () => (_, error) => {
expect(error).toBeUndefined()
},
migrate: (state, version) => {
migrateCallCount++
expect(state.count).toBe(42)
expect(version).toBe(12)
return { count: 99 }
},
})
)

expect(useStore.getState()).toEqual({ count: 99 })
expect(migrateCallCount).toBe(1)
expect(setItemCallCount).toBe(1)
})

it('can throw migrate error', () => {
let postRehydrationCallbackCallCount = 0

const storage = {
getItem: () =>
JSON.stringify({
state: {},
version: 12,
}),
setItem: () => {},
}

const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
getStorage: () => storage,
migrate: () => {
throw new Error('migrate error')
},
onRehydrateStorage: () => (_, e) => {
postRehydrationCallbackCallCount++
expect(e?.message).toBe('migrate error')
},
})
)

expect(useStore.getState()).toEqual({ count: 0 })
expect(postRehydrationCallbackCallCount).toBe(1)
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.