0

I have defined a method to load data from AsyncStorage

const loadFromAsyncStorage = async () => {
  try {
    const serializedState = await AsyncStorage.getItem('state');
    if (serializedState === null) return undefined;

    return JSON.parse(serializedState);
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
    return undefined;
  }
};

Now I would like to persist the state returned into my redux as below

export default class App extends Component {
  render() {
    const persistedState = loadFromAsyncStorage();

    persistedState.then(x => {
      // ??
    });

    const store = createStore(
      reducers, 
      persistedState, 
      applyMiddleware(ReduxThunk)
    );

    store.subscribe(() => saveToAsyncStorage(store.getState()));

    return (
      <Provider store={store}>
        <MainNavigator />
      </Provider>
    );
  }
}

As above, persistedState will be a Promise returned by loadFromAsyncStorage() and the value can only be accessed if I chain .then() or adding a keyword await in front of loadFromAsyncStorage() method. I'm not sure how to achieve it in a render method as I can't make the render method async

Isaac
  • 12,042
  • 16
  • 52
  • 116

1 Answers1

0

The easiest way to use redux-persist for this problem.

You simply need to create a separate store entry for all the app data, and redux-persist handle the persistence of those entries automatically to asyncStorage.

Full working example from Alexander Wolf is on this Codesandbox.

gazdagergo
  • 6,187
  • 1
  • 31
  • 45