0

I'd like to store stuff in redux store, and want to know which one is serializable and which one is not.

  1. class MyClass { }
  2. var myClass = new MyClass

Specifically, are #1, #2 serializable?
What's the test/definition of serializability? Whether JSON.stringify() works without error?

https://github.com/markerikson/redux/blob/create-faq-page/docs/FAQ.md

Can I put functions, promises, or other non-serializable items in my store state?

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store.

eugene
  • 39,839
  • 68
  • 255
  • 489

2 Answers2

2

No. If you want to check if something is serializable, check if object == JSON.parse(JSON.stringify(object));

Here's a few examples I ran in my browser window:

3 == JSON.parse(JSON.stringify(3))
true
"foo" == JSON.parse(JSON.stringify("foo"))
true
class MyClass {}
undefined
MyClass == JSON.parse(JSON.stringify(MyClass))
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data [Learn More]

and in this case it apears that classes can't be serialized at all, since JavaScript just returned undefined.

PaulBGD
  • 2,018
  • 5
  • 22
  • 30
  • This does not work: `{a: 1}` is serializable, but it will not be `==` (since `==` for objects checks referential identity, not equality). You can use one of [these methods](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) to test for deep equality. – Amadan Oct 24 '16 at 02:17
  • Good point, my code only works with primitives. The idea is the same though, if the JSON.parse(JSON.stringify()) output is the same then it's serializable. – PaulBGD Oct 25 '16 at 05:28
0

Methods and functions (and any executable code snippets) can't be serialized, because you can't rehydrate them back wothout using eval.

Dima Vishnyakov
  • 1,361
  • 10
  • 21