elgerlambert / redux-localstorage

Store enhancer that syncs (a subset) of your Redux store state to localstorage.
MIT License
1.32k stars 107 forks source link

State not persisted immediately after a reduce. #24

Closed kiranp11 closed 8 years ago

kiranp11 commented 8 years ago

Hello,

I'm trying to use redux-localstorage@rc I'm facing an issue that an updated state is not being persisted immediately after it is emitted by a reducer.

I went through the code and noticed that persistState is not happening via a subscribe to the store like it was in 0.4.0 but just before a new action is being dispatched using a middleware.

So the current state (in my case result of an async action ) is not persisted until another action is dispatched. What am I missing here?

My create store function looks like this:

function (initialState = {}) {
    var rootReducer = Redux.combineReducers([MDA.tourReducer])
    const reducer = compose(
      mergePersistedState()
    )(rootReducer);
    var createStoreWithMiddleware = Redux.applyMiddleware(MDA.reduxThunkMiddleware)(createStore)
    const createPersistentStore = persistState(storage, "mda")(createStoreWithMiddleware)
    return createPersistentStore(reducer)
}

Thanks in advance

Kiran.

elgerlambert commented 8 years ago

Hi @kiranp11,

Looks like your middleware is in the wrong order. If you re-write to the following it should be okay:

function (initialState = {}) {
    const rootReducer = Redux.combineReducers([MDA.tourReducer])

    const reducer = compose(
      mergePersistedState()
    )(rootReducer);

    const createEnhancedStore = compose(
      Redux.applyMiddleware(MDA.reduxThunkMiddleware),
      persistState(storage, "mda")
    )(createStore);

    return createEnhancedStore(reducer)
}

In this snippet persistState is applied first and applyMiddleware second. Whereas in your code it's the other way around.

kiranp11 commented 8 years ago

Ah! That was the issue. Thanks much for the help!