/* @flow */
import { applyMiddleware, compose, createStore } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import type { Config } from 'redux-persist';

import config from '../config';
import rootReducer from './reducers';
import middleware from './middleware';
import ZulipAsyncStorage from './ZulipAsyncStorage';

// AsyncStorage.clear(); // use to reset storage during development

const store = compose(applyMiddleware(...middleware), autoRehydrate())(createStore)(rootReducer);

const reduxPersistConfig: Config = {
  whitelist: [...config.storeKeys, ...config.cacheKeys],
  // $FlowFixMe: https://github.com/rt2zz/redux-persist/issues/823
  storage: ZulipAsyncStorage,
};

export const restore = (onFinished?: () => void) =>
  persistStore(store, reduxPersistConfig, onFinished);

export default store;

/* @flow */
import { applyMiddleware, compose, createStore } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import type { Config } from 'redux-persist';

import config from '../config';
import rootReducer from './reducers';
import middleware from './middleware';
import ZulipAsyncStorage from './ZulipAsyncStorage';

// AsyncStorage.clear(); // use to reset storage during development

const store = createStore(
  rootReducer,
  undefined,
  compose(applyMiddleware(...middleware), autoRehydrate()),
);

const reduxPersistConfig: Config = {
  whitelist: [...config.storeKeys, ...config.cacheKeys],
  // $FlowFixMe: https://github.com/rt2zz/redux-persist/issues/823
  storage: ZulipAsyncStorage,
};

export const restore = (onFinished?: () => void) =>
  persistStore(store, reduxPersistConfig, onFinished);

export default store;

Rearrange `createStore` call to the form found in docs.
redux: Rearrange `createStore` call to the form found in docs.

This is a pure refactor just based on the Redux API.  The return
value of `applyMiddleware` is a "store enhancer", which the Redux
docs suggest passing as the third argument to `createStore`:
  https://github.com/reduxjs/redux/blob/3cb7b8d55/docs/api/applyMiddleware.md

A "store enhancer" turns out to just be a function you can apply to
`createStore` to produce an alternative `createStore`, and that's
what our existing code does.

Similarly, `autoRehydrate` from redux-persist (v4) is also a "store
enhancer", so their composition is too.  Which is both why our
existing code works, and why this version works.  The example in the
redux-persist docs (such as they are) looks exactly like the version
in this commit:
  https://github.com/rt2zz/redux-persist/tree/v4.10.2

Switch us to the form that more commonly shows up in examples, both
in the Redux docs and the docs of other libraries like redux-persist.
That will simplify comparing things as we migrate to redux-persist v5.
