Yomguithereal / baobab

JavaScript & TypeScript persistent and optionally immutable data tree with cursors.
MIT License
3.15k stars 117 forks source link

Class instance feature lost when altering the state. #497

Closed luccitan closed 7 years ago

luccitan commented 7 years ago

Hello,

I am building a Baobab tree which use Javascript classes for a more convenient way to handle methods shared between different data structures. When I try to modify an object attribute of one of the objects, it loses its class feature and thus the methods inherited in the prototype.

Since I'm validating the data by checking that these objects can call some methods, I can't modify data attributes as I would like to do. An image is worth a thousand words :

image

The second object lost its class feature and is no longer viable after it has been tried to change its ID from 1 to 9. The tree is no longer viable and functionalities are thus lost.

How can I change the attributes while keeping the object as a class instance ?

Yomguithereal commented 7 years ago

Hello @luccitan. Normally, baobab is not meant to hold anything else than "raw" data. Classes aren't therefore supported as it is quite impossible to reliably clone an instance in every JS engine. There are ways to kinda fake cloning instance but they might have some undesirable side effects.

From here, you have another option, if you really want to keep classes: you can disable the tree's persistence (and hence lose its advantages but, it can be done if persistence is not what you need).

var tree = new Baobab({}, {persistent: false});

If you do so, baobab will only mutate objects given and won't try to shift references along the path by cloning.

luccitan commented 7 years ago

It works wonderfully! 👍

Can you explain a little bit more the persistent option please ? I have read through its documentation in the README but I didn't think it was the solution of my problem.

I would appreciate further information about its usefulness, as I may need the tree's history later. (It's not a concern at the moment)

Yomguithereal commented 7 years ago

Persistence is basically useful for 2 use cases:

  1. You need to track the history of the data and may want to go back in time easily.
  2. You need to be able to determine whether two states of the data are identical or not based only on referential equality === without having to perform a diff.
Yomguithereal commented 7 years ago

No. 2 is very useful with view engines like React that can beneficiate from shouldComponentUpdate callbacks that can just check whether references are identical to be able to take the decision to render again or not.

luccitan commented 7 years ago

Does that mean that I can't use baobab-react with a Baobab tree without persistence ? 🤔

Yomguithereal commented 7 years ago

Yes you can. It just means you won’t get pure rendering performance gain (which you dont have by default anyway).