How to use this package with redux-persist
danhddao1997 opened this issue · 0 comments
danhddao1997 commented
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?