When you are using redux-persist in your react application then you come up with an issue that when you change the data structure of any reducer state then it will not appear in your redux state when you reload your application so for that redux-persist provide us a way to update the state using createMigrate method.
To do that you need to create a migration where you provide your updated state so that it will appear in your redux state.
export const migration = {
0: (state: any) => {
return {
...state,
reducerOne:{
...state.reducerOne,
data: null // New value added in reducerOne
}
};
},
};
But lets say you have multiple reducers and you are making changes in lot of reducers as the new feature comes in or some sort of revamp. In that case you will be manually providing all the changes in your migration accordingly. To remove this hectic process there is one simple way first create a constant for Version like this
export const newVersion = 3;
and assign it into migration object, and persistConfig like this:
export const migration = {
[newVersion]: (state: any) => {
return {
...state,
reducerOne:{
...state.reducerOne,
data: null // New value added in reducerOne
}
};
},
};
then in your reducer file where you are assigning your initialState just export it and then import it inside your migration file and assign it against that reducer like this:
import {initialState} from './reducer/reducerOne'
export const migration = {
[newVersion]: (state: any) => {
return {
...state,
reducerOne: initialState,
};
},
};
Now when ever you add, update or delete any property in initialState of reducer, you just need to update the newVersion and reload your react application, after that you will see your updated property will appear in your redux state.
By following this process you don't have to manually enter the properties or reducers in your migration. This architecture will automatically do all the syncing for you.
Hope you like it.
Top comments (0)