KELiON/redux-async-initial-state

Use with React Native and AsyncStorage

flamingo-peacock opened this issue · 5 comments

I can't seem to get this configured correctly to load from Async Storage. As where do I put in other middleware that I am using. Thanks In advance for your help.

@selenarakowski hi! Can you please share your redux store configuration?

import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import reducers from './reducers'
import * as Api from '../lib/api'
import * as asyncInitialState from 'redux-async-initial-state'


const loggerMiddleware = createLogger({predicate : (getState, action) => __DEV__})

const eventLogger = store => next => action => {
  Api.publishEvent(action)
  let result = next(action)
  Api.saveState(store.getState)
  return result
}

function configureStore(initialState) {
  const enhancer = compose(
    applyMiddleware(
      eventLogger,
      thunkMiddleware,
      loggerMiddleware,
    )
  )
  return createStore(reducers, initialState, enhancer)
}

const store = configureStore({})

export default store

This is what it looked like before trying to implement initialState, After trying all sorts of things to get this to work, i gave up and reverted all of my code.

Additional information-
A call from to Api.getStateFromStorage will return a promise containing the initial state.

@selenarakowski I think it should work for you:

//...
// Make sure that you call `combineReducers` only once here, not in ./reducers
const reducer = asyncInitialState.outerReducer(combineReducers({
  ...reducers,
  asyncInitialState: asyncInitialState.innerReducer,
}));
//...
function configureStore(initialState) {
  const enhancer = compose(
    applyMiddleware(
      eventLogger,
      thunkMiddleware,
      loggerMiddleware,
      asyncInitialState.middleware(Api.getStateFromStorage)
    )
  )
  return createStore(reducer, initialState, enhancer)
}

const store = configureStore({})

export default store

So, basically you need to do 3 things:

  • Add middleware asyncInitialState.middleware with argument – function that returns Promise, that is resolved with your initial state
  • Add new key to your reducers object (not function): asyncInitialState: asyncInitialState.innerReducer,
  • Wrap your reducer function to asyncInitialState.outerReducer to get your final reducer;

Ok, If I am not calling combineReducers in ./reducers, what should I be exporting there?

Never mind... I figured it out that it should be an object.

Thank you so much for your help. Everything is working!!!!!