KELiON / redux-async-initial-state

Redux middleware that helps you load redux initial state asynchronously
MIT License
114 stars 12 forks source link

Use with React Native and AsyncStorage #5

Closed flamingo-peacock closed 7 years ago

flamingo-peacock commented 7 years ago

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.

KELiON commented 7 years ago

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

flamingo-peacock commented 7 years ago
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.

KELiON commented 7 years ago

@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:

flamingo-peacock commented 7 years ago

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

flamingo-peacock commented 7 years ago

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

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