Arun kumar
Arun kumar

Reputation: 1081

How to set initial redux state from asynchronous source in react native?

I trying to load all the asynchronous data like user objects from asynchronous storage when the store first-time initialize. But I do not have any idea how to do that. I got one of the suggestions to create a middleware to do this but I don't know-how.

Current Store and its initialization in app

const store = createStore(rootReducer, {}, applyMiddleware(ReduxThunk, 
    //actionCallbackOnceMiddleware(INITIAL_AJAX_END, AppSafeAreaProvider)
    ))

const AppSafeAreaProvider = () => {
    return <Provider store={store}>
            <PaperProvider>
                <SafeAreaProvider>
                        <App />
                </SafeAreaProvider>
            </PaperProvider>
        </Provider>
}

AppRegistry.registerComponent(appName, () => AppSafeAreaProvider);

Upvotes: 0

Views: 563

Answers (2)

Li Sim
Li Sim

Reputation: 216

I'm not sure about the method for setting up redux on React Native since I only use React.js but if you are going to setup your store to handle asynchronous call handlers, your best bet would be to look into middlewares.

https://redux.js.org/api/applymiddleware

Here is an excellent example of how the async requests can be called using the middleware and redux-thunk https://redux.js.org/advanced/async-actions

At the end of the example, it shows how the redux-thunk can be used to initialize your store with an async API call.

Upvotes: 1

ekrem
ekrem

Reputation: 1

You don't need default state globally because reducers already have a default state parameter on redux

For example

const someReducer = (defaultState = {foo: 'bar'}, action) => {
  switch(action.parameter)
  {
    ...
    default return defaultState
  }
}

Your state

{
   someReducer: { foo: 'bar' }
}

Upvotes: 0

Related Questions