nrofis
nrofis

Reputation: 9766

Use immer `MapSet` plugin with redux toolkit

I have some slices that use Sets in their state. I have this code:

import { configureStore } from '@reduxjs/toolkit';
import { enableMapSet } from 'immer';
import { reducers } from './reducers';

enableMapSet();

export function configureStore() {
    const rootReducer = combineReducers({
        ...reducers,
    });

    return configureStore({
        reducer: rootReducer,
    });
}

const store = configureStore();
export type AppDispatch = typeof store.dispatch;
export default store;

Although I installed the immer and call enableMapSet(), I still get an error when my app loaded:

Unhandled Rejection (Error): [Immer] The plugin for 'MapSet' has not been loaded into Immer. To enable the plugin, import and call enableMapSet() when initializing your application.

How should I configure the enableMapSet with Redux Toolkit?

Upvotes: 20

Views: 21447

Answers (2)

manroe
manroe

Reputation: 1775

The previously accepted answer was at least helpful for me to figure out the issue I was having, similar to OP.

I have been storing Maps in older versions of Redux for a long time without issues, I see the statement that you should not do this all over the internet but it's hardly ever justified with reasons. The one reason I see occasionally is that they aren't serializable. However, I don't save my Redux state to e.g. LocalStorage so the serializable concerns don't seem to affect me.

To solve OP's problem, given the accepted answer's advice that there may be more than one version of immer present in my application, I went to my yarn.lock file to see which version @reduxjs/toolkit was depending on (7.0.3 as of reduxjs/[email protected]) and made sure the one I added to my own package.json was the same. (yarn add immer installed a newer version of immer than Redux uses).

Once I made that change, my call to enableMapSet() got rid of the error OP and I had.

Upvotes: 13

markerikson
markerikson

Reputation: 67469

Two thoughts here:

Upvotes: 12

Related Questions