How to create a redux store with local data storage?

352 Views Asked by At

I am confused by the docs. I am trying to use Redux-storage middleware and this is how they show the store is created with the middleware:

const middleware = storage.createMiddleware(engine);
const createStoreWithMiddleware = applyMiddleware(middleware)(createStore);
const store = createStoreWithMiddleware(reducer);

But the Redux docs show this:

let store = createStore(
  todos,
  [ 'Use Redux' ], // How do I put here the data from the redux-storage?
  applyMiddleware(middleware) // here goes the redux-storage
)

createStore requires an initial store value to be passed, but I can't load the stored values without having a store. This is a kind of catch 22. What did I miss here?

1

There are 1 best solutions below

1
On

You actually miss nothing and that is intended behavior of redux-storage: there is a gap between creating redux store and the moment it got filled with the stored data. That is because storage engine provided to redux-storage createLoader can have an async nature in general case.

The common pattern to deal with that is following:

  1. Your app starts up with uninitialized store state
  2. It shows some kind of a preloader to your user
  3. App creates loader and loads stored state: const load = storage.createLoader(engine); load(store);
  4. Wait store to be rehydrated and hide preloader.

There is another store peristing lib out there: redux-persist. But initialization process works the same way, except you don't have to call load explicitly.