question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Initializing Redux state with AsyncStorage

See original GitHub issue

I 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:closed
  • Created 7 years ago
  • Reactions:8
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

13reactions
rt2zzcommented, Dec 16, 2016

persistStore + autoRehydrate will handle all of that for you. In your case config should probably be { storage: AsyncStorage }

// @NOTE make sure autoRehydrate needs to be set up in configureStore

class App extends Component {
  componentWillMount(){
    persistStore(store, { storage: AsyncStorage }, () => {
      this.setState({ rehydrated: true })
    })
  }
  render() {
    if (!this.state.rehydrate) return <Text>Loading...</Text>
    return (
      <Provider store={store}>
        <Router />
      </Provider>
    );
  }
}

export default App;
9reactions
rt2zzcommented, Dec 15, 2016

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:

class App extends Component {
  componentWillMount(){
    persistStore(store, config, () => {
      this.setState({ rehydrated: true })
    })
  }
  render() {
    if (!this.state.rehydrate) return <Text>Loading...</Text>
    return (
      <Provider store={store}>
        <Router />
      </Provider>
    );
  }
}

export default App;
Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I populate the initialState in Redux from react native's ...
I am storing username and uid in AsyncStorage so they don't have to log in every time. How do I populate the initialState...
Read more >
How to use Redux Persist in React Native - LogRocket Blog
In React Native applications, data can be persisted locally using AsyncStorage . AsyncStorage is an asynchronous, persistent, key-value storage ...
Read more >
How To Use Redux Persist in React Native with Asyncstorage
The Redux Persist library provides an easy way to save a Redux store in the local storage of React Native apps. In this...
Read more >
Using redux-toolkit with redux-persist for React Native
import AsyncStorage from '@react-native-async-storage/async-storage';. Now we need to decide which reducer of the redux store we need to persist ...
Read more >
Integrate Redux Toolkit, Redux persist, and React-Native ...
expo init rn-redux-boilerplate. Once it is done, then we will install redux ... Redux persist will save the state in our local AsyncStorage....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found