fix(persist): #409 (#470)

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
This commit is contained in:
Anatole Lucet 2021-06-29 14:27:56 +02:00 committed by GitHub
parent 9774360900
commit 08f5d83393
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 62 additions and 2 deletions

View File

@ -160,7 +160,7 @@ export type StateStorage = {
getItem: (name: string) => string | null | Promise<string | null>
setItem: (name: string, value: string) => void | Promise<void>
}
type StorageValue<S> = { state: S; version: number }
type StorageValue<S> = { state: S; version?: number }
type PersistOptions<S, PersistedState extends Partial<S> = Partial<S>> = {
/** Name of the storage (must be unique) */
name: string
@ -181,6 +181,7 @@ type PersistOptions<S, PersistedState extends Partial<S> = Partial<S>> = {
serialize?: (state: StorageValue<S>) => string | Promise<string>
/**
* Use a custom deserializer.
* Must return an object matching StorageValue<State>
*
* @param str The storage's current value.
* @default JSON.parse
@ -358,7 +359,10 @@ export const persist =
})
.then((deserializedStorageValue) => {
if (deserializedStorageValue) {
if (deserializedStorageValue.version !== version) {
if (
typeof deserializedStorageValue.version === 'number' &&
deserializedStorageValue.version !== version
) {
if (migrate) {
return migrate(
deserializedStorageValue.state,

View File

@ -355,4 +355,36 @@ describe('persist middleware with async configuration', () => {
},
})
})
it("can merge the state when the storage item doesn't have a version", async () => {
const storage = {
getItem: async () =>
JSON.stringify({
state: {
count: 1,
},
}),
setItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
deserialize: (str) => JSON.parse(str),
})
)
function Counter() {
const { count } = useStore()
return <div>count: {count}</div>
}
const { findByText } = render(<Counter />)
await findByText('count: 1')
expect(useStore.getState()).toEqual({
count: 1,
})
})
})

View File

@ -277,4 +277,28 @@ describe('persist middleware with sync configuration', () => {
},
})
})
it("can merge the state when the storage item doesn't have a version", () => {
const storage = {
getItem: () =>
JSON.stringify({
state: {
count: 1,
},
}),
setItem: () => {},
}
const useStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
getStorage: () => storage,
deserialize: (str) => JSON.parse(str),
})
)
expect(useStore.getState()).toEqual({
count: 1,
})
})
})