Skip to content

Fix HMR state reset for objects stores (#2931) #2958

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

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from
Open
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
52 changes: 47 additions & 5 deletions packages/pinia/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,12 +598,55 @@ function createSetupStore<
newStore.$state[stateKey] = oldStateSource
}
}
// patch direct access properties to allow store.stateProperty to work as
// store.$state.stateProperty
// @ts-expect-error: any type
store[stateKey] = toRef(newStore.$state, stateKey)
})

// Update state and sync properties
if (options && 'state' in options) {
// // For option stores
const currentState = pinia.state.value[$id]
// Remove deleted properties
Object.keys(currentState).forEach((key) => {
if (!(key in newStore.$state)) {
delete currentState[key]
}
})
// Assign new state properties, preserving reactivity of the existing object
assign(currentState, newStore.$state)

// Remove all old direct state properties from store
store._hmrPayload.state.forEach((oldStateKey) => {
if (!(oldStateKey in newStore.$state)) {
/// @ts-expect-error any
delete store[oldStateKey]
}
})

// Add new direct state properties
newStore._hmrPayload.state.forEach((stateKey) => {
// patch direct access properties to allow store.stateProperty to work as
// store.$state.stateProperty
// @ts-expect-error: any type
store[stateKey] = toRef(pinia.state.value[$id], stateKey)
})
} else {
// For setup stores, use hotState
pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState')

store._hmrPayload.state.forEach((oldStateKey) => {
if (!(oldStateKey in newStore.$state)) {
/// @ts-expect-error any
delete store[oldStateKey]
}
})
// Sync direct properties for setup stores
newStore._hmrPayload.state.forEach((stateKey) => {
// patch direct access properties to allow store.stateProperty to work as
// store.$state.stateProperty
// @ts-expect-error: any type
store[stateKey] = toRef(pinia.state.value[$id], stateKey)
})
}

// remove deleted state properties
Object.keys(store.$state).forEach((stateKey) => {
if (!(stateKey in newStore.$state)) {
Expand All @@ -615,7 +658,6 @@ function createSetupStore<
// avoid devtools logging this as a mutation
isListening = false
isSyncListening = false
pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState')
isSyncListening = true
nextTick().then(() => {
isListening = true
Expand Down