I'm using Ionic 7, React 18, and Redux-Toolkit and Redux-Persist. I would like to persist one of my states (cart) to local storage. I have set up my cartSlice as below
interface CartState {
[key: string]: OrderItem[];
}
const initialState: CartState = {};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
...
},
clearCart: (state) => {
...
},
},
});
export const {
addToCart,
clearCart,
} = cartSlice.actions;
export default cartSlice.reducer;
and set up my root persist reducer as below
const rootPersistConfig = {
key: 'root',
storage: storage,
blacklist: ['auth'],
stateReconciler: autoMergeLevel2
};
const authPersistConfig = {
key: 'auth',
storage: sessionStorage,
}
const rootReducer = combineReducers({
auth: persistReducer(authPersistConfig, authReducer),
cart: cartReducer,
})
const persistedReducer = persistReducer(rootPersistConfig, rootReducer);
export default persistedReducer;
in which I load this into my store like below
export const store = configureStore({
reducer: persistedReducer, // rootReducer,
devTools: import.meta.env.VITE_NODE_ENV !== "production",
});
What I'm not clear about is how to set my initial state to be local storage, assuming there is already something there. Every time I load my app, my initial state is reset to "{}", due to how I set it in my slice, but I can't figure out how to tell my state that the initial state can be loaded from local storage, if the state is already there.
Ensure that you are following all of the setup/configuration steps.