Replies: 4 comments
-
|
The |
Beta Was this translation helpful? Give feedback.
-
|
dai-shi is right — For migrating from Redux-Persist / Vuex / localStorage keys, implement a custom import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
const migratingStorage = createJSONStorage(() => localStorage, {
getItem: (name) => {
// Check if Zustand already has state under this key
const existing = localStorage.getItem(name);
if (existing) return existing;
// First load — merge from old storage keys
const oldUser = JSON.parse(localStorage.getItem('user') ?? 'null');
const oldSettings = JSON.parse(localStorage.getItem('settings') ?? 'null');
const oldCart = JSON.parse(localStorage.getItem('cart') ?? 'null');
if (!oldUser && !oldSettings && !oldCart) return null;
const merged = {
state: {
user: oldUser,
settings: oldSettings,
cart: oldCart,
},
version: 0,
};
// Write merged state so this only runs once
localStorage.setItem(name, JSON.stringify(merged));
return JSON.stringify(merged);
},
});
const useAppStore = create(
persist(
(set) => ({
user: null,
settings: {},
cart: [],
}),
{
name: 'app-store',
storage: migratingStorage,
version: 0,
}
)
);The custom If your old data needs transformation (different field names, nested structure, etc.), do that in the merge step before writing. |
Beta Was this translation helpful? Give feedback.
-
|
The previous comments are on the right track. Here's a complete, copy-pasteable solution. Why
|
Beta Was this translation helpful? Give feedback.
-
|
Thank you everyone, I have solved the migration issue by customizing the storage. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Scene:
The project was migrated from other state management libraries (such as Redux-Persist, Vuex, and LocalStorage) to Zustand.
The old data is distributed across multiple independent storage keys (e.g., user, settings, cart).
After migrating to Zustand, these scattered data need to be read and merged as the initial state of the Zustand store.
Current problem:
On the first load, migrate will not be executed at all, and it will be unable to read data from other keys for merging.
Beta Was this translation helpful? Give feedback.
All reactions