[QUESTION] Initializing Redux state with AsyncStorage
See original GitHub issueI am building a React Native app, and I want to initialize my redux state so that my login/register component only renders if a user’s device does not have a token stored in AsyncStorage.
I have several reducers and have combined them in a file called /reducers/index.js
with the redux method combineReducers
. My auth
reducer has a key called loggedIn which is either true or false. I am using this particular key from my auth reducer to display my login/registration component.
I have read the examples, but I am having a hard time getting this to work. This is what I have so far in my top level component.
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import Logger from 'redux-logger';
import { AsyncStorage } from 'react-native';
import reducers from './reducers';
import Router from './Router';
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk, Logger()));
class App extends Component {
render() {
return (
<Provider store={store}>
<Router />
</Provider>
);
}
}
export default App;
Essentially what I would like to do is call AsyncStorage.getItem('uniqueUserToken')
and if it returns a string, then initialize auth.loggedIn
to true. But if it returns null
then initialize loggedIn to false, or even just an empty object.
I have found it quite easy to do on the web with localStorage, which is synchronous, but I cannot wrap my head around this particular challenge. How could I achieve this using redux-persist? Thank you for creating a great package, and I look forward to getting it to work in my project.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:8
- Comments:7 (3 by maintainers)
persistStore + autoRehydrate will handle all of that for you. In your case config should probably be
{ storage: AsyncStorage }
as you have observed the async nature of AsyncStorage (and localForage on web) make this something of a challenge, however I think this is a good thing, as async access is the only sane way to read from disk for large quantities of data.
In this case you are going to want to defer loading Router until after state has persisted. The simplest way to do this is as follows: