Search code examples
javascriptreactjsreact-nativereduxasyncstorage

Async Storage in React Native showing only first time saved data


I am trying to save data into async storage every time when data in redux store changes, But I am getting an error when I am trying to update user's Name and saving it then I am able to see the changes when Application is open but when I close the application and open it again then it is showing the Old User's Name that I have updated.

For example if my current Name is "Aviansh" and I have updated it to "Anshu" then I am to see "Anshu" when Application is open but when I close the application and open it again then I am able to see "Avinash" again that is not expected

Code for saving Data in Local Storage

import AsyncStorage from '@react-native-community/async-storage';

export const loadState = async () => {
  try {
    const serializedState = await AsyncStorage.getItem('socialReduxState');
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};


export const saveState = async (state) => {
  try {
    const serializedState = JSON.stringify(state);
    await AsyncStorage.setItem('socialReduxState', serializedState);
  } catch (err) {
    console.log('Error has occurred: ', err);
  }
}

Code in Redux Store

import { createStore, applyMiddleware } from 'redux';
// thunk allows multiple actions to be run together
import thunk from 'redux-thunk';

import rootReducer from './reducers';
import { loadState, saveState } from './localStorage';

// Get existing state from localStorage
const persistedState = {};
// Create Store with data
const store = createStore(
  rootReducer,
  persistedState,
  applyMiddleware(thunk)
);

// Listen for any changes to the state and update localStorage
store.subscribe(() => {
  saveState(store.getState());
});


export default store;


Solution

  • You have mentioned in the comments that you use redux-persist, but in the code sample you have posted, there is no redux-persist setup - this is what you are missing.

    There is no need to save/load the data from async storage manually if you are using redux-persits, just follow the instructions in the package readme carefully.

    import { createStore, applyMiddleware } from 'redux'
    import { persistStore, persistReducer } from 'redux-persist'
    import AsyncStorage from '@react-native-community/async-storage'
    import thunk from 'redux-thunk'
    
    import rootReducer from './reducers'
    
    const persistConfig = {
      key: 'root',
      storage: AsyncStorage,
    }
    
    const persistedReducer = persistReducer(persistConfig, rootReducer)
    
    const store = createStore(persistedReducer, {}, applyMiddleware(thunk))
    const persistor = persistStore(store)
      
    export { store, persistor }
    
    // Then use the `persistor` in your root app component:
    
    import { PeristGate } from 'reds-persist'
    import { store, persistor } from './store'
    
    const App = () => {
      return (
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            {... your root app component here ...}
          </PersistGate>
        </Provider>
      );
    };