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

How to use this package with redux-persist #119

@danhddao1997

Description

@danhddao1997

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions