diff --git a/docs/migrations.md b/docs/migrations.md index 83f5415df..97a8be997 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -13,7 +13,8 @@ const migrations = { device: undefined } }, - 1: (state) => { + // Async functions are allowed + 1: async (state) => { // migration to keep only device state return { device: state.device diff --git a/src/createMigrate.ts b/src/createMigrate.ts index 78dcce05a..9ca362267 100644 --- a/src/createMigrate.ts +++ b/src/createMigrate.ts @@ -8,14 +8,14 @@ export default function createMigrate( config?: { debug: boolean } ): (state: PersistedState, currentVersion: number) => Promise { const { debug } = config || {} - return function( + return async function ( state: PersistedState, currentVersion: number ): Promise { if (!state) { if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: no inbound state, skipping migration') - return Promise.resolve(undefined) + return undefined } const inboundVersion: number = @@ -25,7 +25,7 @@ export default function createMigrate( if (inboundVersion === currentVersion) { if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: versions match, noop migration') - return Promise.resolve(state) + return state } if (inboundVersion > currentVersion) { if (process.env.NODE_ENV !== 'production') @@ -40,18 +40,17 @@ export default function createMigrate( if (process.env.NODE_ENV !== 'production' && debug) console.log('redux-persist: migrationKeys', migrationKeys) - try { - const migratedState: any = migrationKeys.reduce((state: any, versionKey) => { - if (process.env.NODE_ENV !== 'production' && debug) - console.log( - 'redux-persist: running migration for versionKey', - versionKey - ) - return migrations[versionKey](state) - }, state) - return Promise.resolve(migratedState) - } catch (err) { - return Promise.reject(err) + let migratedState: any = state + + for (const versionKey of migrationKeys) { + if (process.env.NODE_ENV !== 'production' && debug) + console.log( + 'redux-persist: running migration for versionKey', + versionKey + ) + migratedState = await migrations[versionKey](migratedState) } + + return migratedState } } diff --git a/src/types.ts b/src/types.ts index 8e83b67e6..73237c51e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -84,7 +84,9 @@ export interface WebStorage extends Storage { } export interface MigrationManifest { - [key: string]: (state: PersistedState) => PersistedState; + [key: string]: + | ((state: PersistedState) => PersistedState) + | ((state: PersistedState) => Promise) } /**