Skip to content
This repository has been archived by the owner on Nov 7, 2023. It is now read-only.

How to use this package with redux-persist #119

Open
danhddao1997 opened this issue Jul 27, 2023 · 0 comments
Open

How to use this package with redux-persist #119

danhddao1997 opened this issue Jul 27, 2023 · 0 comments

Comments

@danhddao1997
Copy link

Hello, I'm currently trying to use this package with redux-persist, below is my code

store.ts

import {combineReducers, configureStore} from '@reduxjs/toolkit';
import persistedReducer from './persistedSlice';
import {
  FLUSH,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
  REHYDRATE,
  persistReducer,
  persistStore,
} from 'redux-persist';
import EncryptedStorage from 'react-native-encrypted-storage';
import {TypedUseSelectorHook, useDispatch, useSelector} from 'react-redux';

const combinedReducer = combineReducers({
  persisted: persistedReducer,
});

const persistedCombinedReducer = persistReducer(
  {
    key: 'root',
    storage: EncryptedStorage,
    whitelist: ['persisted'],
  },
  combinedReducer,
);

const createStores = () => {
  const store = configureStore({
    reducer: persistedCombinedReducer,
    middleware: getDefaultMiddleware =>
      getDefaultMiddleware({
        serializableCheck: {
          ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
        },
      }),
  });

  const persistedStore = persistStore(store);

  return {store, persistedStore};
};

const {store, persistedStore} = createStores();

export {store, persistedStore};

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

type DispatchFunc = () => AppDispatch;
export const useAppDispatch: DispatchFunc = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

persistedSlice.ts

import {PayloadAction, createSlice} from '@reduxjs/toolkit';

interface PersistedState {
  user?: {
    id: string;
    name: string;
  };
  token?: string;
}

const initialState: PersistedState = {};

const persistedSlice = createSlice({
  name: 'persisted',
  initialState,
  reducers: {
    setPersistedData(state, action: PayloadAction<PersistedState>) {
      console.log('AAAA: ', {
        state,
        data: action.payload,
      });
      state = action.payload;
    },
  },
});

export const {setPersistedData} = persistedSlice.actions;

export default persistedSlice.reducer;

When I called setPersistedData, the state does not update.

Is there anything I'm doing wrong?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant