Redux Persist + Redux toolkit $CombinedState error

Viewed 925

I'm trying to add redux persist to redux toolkit but for some reason I get an Exported variable 'store' has or is using name '$CombinedState' from external module ".../node_modules/redux/index" but cannot be named. error on vscode.

This is my store configuration file with the added persist config, which if I remove, works fine.

import { configureStore } from "@reduxjs/toolkit";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { createEpicMiddleware } from "redux-observable";
import rootEpic from "onsite/redux/rootEpic";
import rootReducer from "onsite/redux/rootReducer";

const epicMiddleware = createEpicMiddleware();

const persistConfig = {
  key: "root",
  storage: storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

// Line that shows error
const store = configureStore({
  reducer: persistedReducer,
  middleware: [epicMiddleware],
});

export default store;

epicMiddleware.run(rootEpic);

Other things I have tried are putting the combineReducers declaration (from rootReducerimport) into the same file or converting the file into plain javascript, with same or similar results. For some reason typescript decides to still haunt me on a javascript file :)

The code still runs, so I'm tempted to leave it like that, but I would like to get rid of it.

2 Answers

I had the same issue, and here's what I figured out:

You need to include Store from redux, and use it as your type definition for your own store return value. Short answer:

import { Store } from 'redux';
[...]
const store:Store = configureStore([...])
[...]
export default store;

Longer answer:

As I understand it, what was happening is that Store type uses $CombinedState as part of its definition. When configureStore() returns, it inherits the State type. However since State is not explicitly used in your code, that now means that your code includes a value that references $CombinedState, despite it not existing anywhere in your code either. When you then try to export it out of your module, you're exporting a value with a type that doesn't exist within your module, and so you get an error.

You can import State from redux (which will in turn explicity cause your code to bring in $CombinedState), then use it to explicitly define store that gets assigned the return of configureStore(). You should then no longer be exporting unknown named types.

You can also be more specific with your Store type, as it is a generic:

const store:Store<RootState>

Although I'm not entirely sure if that would be a circular dependency, since your RootState depends on store.

Adding a

import { $CombinedState } from '@reduxjs/toolkit'

in that file should usually resolve that error.

Related