Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
like image 644
user1099123 Avatar asked Dec 20 '25 20:12

user1099123


1 Answers

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.

like image 92
phry Avatar answered Dec 23 '25 10:12

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!