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

How to hydrate with a global variable? #30

Closed silouanwright closed 8 years ago

silouanwright commented 8 years ago

So my application has some data that I'm trying to pass to Redux, so I put it on window and I'm trying to merge it in:

mergePersistedState((initialState, persistedState) => {
            return merge({}, initialState, persistedState, { awesome: window.awesome })
}),

The only problem is I'm pretty sure this only hydrates on refresh (or at least not initially). So how would I do this in the redux-localstorage setup to where it hydrates immediately on first load?

elgerlambert commented 8 years ago

Hi @reywright,

Rather then creating a custom mergePersistedState reducer you should be able to simply supply your data to createStore as initialState, e.g.:

const initialState = { awesome: window.awesome };

const store = createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(...middleware),
      persistState(storage, 'my-key'),
    )
  );

But the issue you describe kind of sounds like a race condition, is window.awesome loaded asynchronously and perhaps cached after you reload..? I don't see why the code you had wouldn't work.

Let me know if this is still an issue for you!

elgerlambert commented 8 years ago

Closing this for now, but definitely let me know if you still need help!