Skip to content

Commit

Permalink
fix(storage): avoid calling setItem with the state just retrieved (#2678
Browse files Browse the repository at this point in the history
)
  • Loading branch information
double-thinker authored Aug 15, 2024
1 parent a56e76d commit dad3641
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/middleware/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,27 +459,34 @@ const newImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {
deserializedStorageValue.version !== options.version
) {
if (options.migrate) {
return options.migrate(
deserializedStorageValue.state,
deserializedStorageValue.version,
)
return [
true,
options.migrate(
deserializedStorageValue.state,
deserializedStorageValue.version,
),
] as const
}
console.error(
`State loaded from storage couldn't be migrated since no migrate function was provided`,
)
} else {
return deserializedStorageValue.state
return [false, deserializedStorageValue.state] as const
}
}
return [false, undefined] as const
})
.then((migratedState) => {
.then((migrationResult) => {
const [migrated, migratedState] = migrationResult
stateFromStorage = options.merge(
migratedState as S,
get() ?? configResult,
)

set(stateFromStorage as S, true)
return setItem()
if (migrated) {
return setItem()
}
})
.then(() => {
// TODO: In the asynchronous case, it's possible that the state has changed
Expand Down
22 changes: 22 additions & 0 deletions tests/persistSync.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -738,4 +738,26 @@ describe('persist middleware with sync configuration', () => {
undefined,
)
})

it('does not call setItem when hydrating from its own storage', async () => {
const setItem = vi.fn()
const storage = {
getItem: (name: string) => ({
state: { count: 42, name },
version: 0,
}),
setItem,
removeItem: () => {},
}

const useBoundStore = create(
persist(() => ({}), {
name: 'test-storage',
storage: storage,
}),
)

expect(useBoundStore.persist.hasHydrated()).toBe(true)
expect(setItem).toBeCalledTimes(0)
})
})

0 comments on commit dad3641

Please sign in to comment.