user1099123
user1099123

Reputation: 6683

Why is a Map in JS considered non serializable in redux?

When using redux and you try to store a map into it, you get an error:

A non-serializable value was detected in the state

Why is that? I know the doc says you can't but it doesn't explain why. Because you can't directly JSON.stringify a map? But you can do something like this...

m = new Map()
m.set("1", "2")
JSON.stringify([...m]);

Upvotes: 3

Views: 2653

Answers (1)

phry
phry

Reputation: 44136

A map can under specific cirumstances be serializable and de-serializable if you provide the logic by that by hand, using map.entries() and Map.fromEntries(...).

Assuming that all keys and values of the map are themselves serializable - which is not necessarily the case, since maps can take any object as a key (and value, of course).

It cannot be serialized automatically by calling JSON.serialize in a way that would allow you to reconstruct it by calling JSON.parse - and that is what most tools rely on.

So, using a Map could break middleware like redux-persist (unless you add more logic there) and countless others and sometimes even (depending on what you put in here and what you use as keys) even go so far as to crash your DevTools.

Since a map that only contains serializable values & keys has no real benefits over just using a normal object for the same purpose, we recommend just using plain JavaScript objects instead of maps.

Upvotes: 2

Related Questions