I'm using redux-toolkit and I'm trying to save my state to local storage after each update of the store without using any third-parties libraries. The reason for this is redux-persist is no longer updated and I don't know any good alternative. After lots of time looking for solution, I came up with using createListenerMiddleware
.
import { configureStore, createListenerMiddleware } from "@reduxjs/toolkit";
import counterSlice, { decrement, increment } from "../Slices/counterSlice";
const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: increment,
effect: () => (
localStorage.setItem('count', JSON.stringify(store.getState().counter))
)
})
const listenerMiddleware2 = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: decrement,
effect: () => (
localStorage.setItem('count', JSON.stringify(store.getState().counter))
)
})
const counterState = JSON.parse(localStorage.getItem('count') || "null")
export const store = configureStore({
preloadedState: {
counter: counterState === null ? { value: 0 } : counterState
},
reducer: {
counter: counterSlice
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(listenerMiddleware2.middleware, listenerMiddleware.middleware)
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
Could someone tell me if this is a good idea, and if not, is there any other way of doing it properly.