async migrate
will result in Data Loss
#2827
-
Bug DescriptionUsing an import { create, StateCreator } from 'zustand';
import { persist } from 'zustand/middleware';
type StoreState = {
example: string;
};
const store: StateCreator<StoreState> = () => ({
example: 'initial',
});
export const useAsyncStore = create<StoreState>()(
persist(store, {
name: 'ASYNC_STORE',
version: 1, // must be raised to 2 after once persisted
migrate: async (persistedState, version) => {
const migratedState = persistedState as StoreState;
if (version < 2) {
migratedState.example = await new Promise((resolve) => {
setTimeout(() => {
resolve('migrated ✅');
}, 100);
});
}
console.log('async migrate result', JSON.stringify(migratedState));
return migratedState;
},
})
); And compare to this non-async import { create, StateCreator } from 'zustand';
import { persist } from 'zustand/middleware';
type StoreState = {
example: string;
};
const store: StateCreator<StoreState> = () => ({
example: 'initial',
});
export const useSyncStore = create<StoreState>()(
persist(store, {
name: 'SYNC_STORE',
version: 1, // must be raised to 2 after once persisted
migrate: (persistedState, version) => {
const migratedState = persistedState as StoreState;
if (version < 2) {
migratedState.example = 'migrated ✅';
}
console.log('sync migrate result', JSON.stringify(migratedState));
return migratedState;
},
})
); When there is a persisted value in the storage and raising the 0. Initially displayedResult:
1. Click Button to initially persist storesResult:
2. Manually change version in both stores to 2Result:
→ Both stores should have changed the value to This is broken from >= 4.5.5 upwards (I've reproduced with 4.5.5, 5.0.0 and 5.0.1), similarly to the behavior change #2763 I suspect #2678, to have broken this functionality. If I'm not doing something wrong this should be quite prominently announced. People are facing data loss, if they have an Reproduction Linkhttps://stackblitz.com/edit/vitejs-vite-jd3xf5?file=src%2FuseAsyncStore.ts |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
Thanks for reporting. Nice catch. |
Beta Was this translation helpful? Give feedback.
@dai-shi @KiwiKilian here you go -> #2877