Redux-Persist in Typescript without react

Viewed 42

I wanna use the redux store with redux-persist without react.

Here's my code:

store.ts

import {combineReducers, configureStore} from "@reduxjs/toolkit";
import {slice} from "../counter/counterSlice";
import storage from 'redux-persist/lib/storage';
import {persistReducer, persistStore} from 'redux-persist';

const persistConfig = {
    key: 'root',
    storage,
}

const rootReducer = combineReducers({
    counter: slice.reducer
});

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production'
})

export const persistor = persistStore(store)

app.ts

import {getCount, incrementCount} from "./counter/counter";

console.log(getCount())
incrementCount()
incrementCount()
incrementCount()
incrementCount()
incrementCount()
console.log(getCount())

counter.ts

import {store} from "../redux/store";
import {slice as counterSlice } from "./counterSlice";

export function getCount(): number {
    const state = store.getState();
    return state.counter.value;
}

export function incrementCount() {
    store.dispatch(counterSlice.actions.increment());
}

counterSlice.ts

import { createSlice } from "@reduxjs/toolkit";

export const slice = createSlice({
    name: "counter",
    initialState: {
        value: 0
    },
    reducers: {
        increment: (state) => {
            state.value += 1;
        }
    }
});

I see in the localstorage the persited data: localstorage

But the counter is always starting at 0: console

It seems the Rehydration isn't working. Have you any ideas how I can solve the problem?

Thank you very much.

0 Answers
Related