0

I am using react, redux persist, and redux-starter-kit.

My server is returning data like the following :

'key1':'value1'
'key2':'value2' 
'key3':'value3'  
}

The problem is, I setup those value as Map in the states, but redux is totally ignoring those value because they are not serializable. (or returning an object and not a map)

I am ok with storing a plain object, but I would like to know if there is a way to add an interface for this kind of object. If I use a type object, it will be to generic, I would like to store something like object

Is this possible ?

I want

Bobby
  • 4,372
  • 8
  • 47
  • 103

2 Answers2

0

For plain object, as it says in the docs of typescript, you can do:

interface IObject {
    key1: 'value1';
    key2: 'value2';
    key3: 'value3';
}

const object: IObject = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
};

For Map, It as already answers here, you can do something like:

type keys = "key1" | "key2" | "key3"
type values = "value1" | "value2" | "value3"

const map = new Map<keys, values>();
map.set('key1', "value1");
map.set('key2', "value2");
Ditiz
  • 171
  • 2
  • 12
0

I guess your problem is with redux-persist not persisting your state because it is an ES6 Map which is not supported by it.

If so, you may add a transformer to your persist configuration object. Something like this:

const persistConfig = {
  <your configuration>,
  transforms: [createTransform(
    map => Array.from(map),
    array => new Map(array),
    { whitelist: ['<your Map property name>'] }
  )],
}

If your whole state is a Map you can avoid using the whitelist property.

Federico Bellucci
  • 623
  • 2
  • 7
  • 26