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(storage): avoid calling setItem with the state just retrieved #2678

Merged
merged 1 commit into from
Aug 15, 2024
Merged
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
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)
})
})
Loading