rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

Library not working on React Native #1349

Closed Rohan-Rajesh closed 2 years ago

Rohan-Rajesh commented 2 years ago

I installed and setup the library but it does not seem to persist my data I tried to add the persistConfig variable t root reducer as well as my individual reducer file... I'm still not sure which is the right way yet Anyway, Here is my code:

store.ts:

import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {persistStore} from 'redux-persist';

import authReducer from './reducers/authReducer';
import toastReducer from './reducers/toastReducer';

const rootReducer = combineReducers({
  toast: toastReducer,
  auth: authReducer,
});

export const Store = createStore(rootReducer, applyMiddleware(thunk));
export const PersistedStore = persistStore(Store);

export type RootState = ReturnType<typeof Store.getState>;
export type AppDispatch = typeof Store.dispatch;

authReducer.ts:

import AsyncStorage from '@react-native-async-storage/async-storage';
import {persistReducer} from 'redux-persist';

import {AuthResponse} from '../../types/AuthResponse';
import {AuthReduxAction} from '../../types/ReduxActions';
import {SET_USER_DETAILS} from '../constants';

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
};

interface State {
  userDetails: AuthResponse;
}

const initialState: State = {
  userDetails: {},
};

const authReducer: (
  state: State,
  action: AuthReduxAction,
) => State | Promise<State> = async (state = initialState, action) => {
  switch (action.type) {
    case SET_USER_DETAILS:
      return {...state, userDetails: action.payload};
    default:
      return state;
  }
};

export default persistReducer(persistConfig, authReducer);

App.tsx

import React from 'react';
import Routes from './Routes';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';

import {PersistedStore, Store} from './redux/store';

const App = () => {
  return (
    <Provider store={Store}>
      <PersistGate loading={null} persistor={PersistedStore}>
        <Routes />
      </PersistGate>
    </Provider>
  );
};

export default App;

When I print out the data form the redux state, here is what I get: {"_U": 0, "_V": 0, "_W": null, "_X": null, "_persist": {"rehydrated": true, "version": -1}}

Any help in how to set this up would be appreciated, Thanks

rb3198 commented 2 years ago

@Rohan-Rajesh did you find the solution to this problem ? Faced the same issue, interested in the fix.