theKashey / proxyequal

There is a bit more smart way to compare things, than a shallow equal.
MIT License
72 stars 7 forks source link

Add support for primitives (TypeError: Attempted to add a non-object key to a WeakSet) #27

Open pie6k opened 4 years ago

pie6k commented 4 years ago

I'm very happy using proxyEqual in my project.

I've created a few react hooks based on it and the way it can optimize renders is crazy!

However, I sometimes use it in generic hooks, where I don't know up-front what type of value will be used for the state.

And if it'll happen that such value will be primitive (eg. string, null), ProxyEqual will throw an error

TypeError: Attempted to add a non-object key to a WeakSet

add
    [native code]:0
proxyfy
    proxyEqual.js:133:21
proxyState
    proxyEqual.js:555:30
...

I've mitigated this issue by always wrapping my value inside a small object like { __value: valueHere }, but it's probably not the optimal way to do it as it's always adding one level of nesting when comparing anything.

I've tried to dynamically detect if I need such wrapper and wrap it or no when creating a proxy initially, but this also didn't work, as often state that used to be null, might become an object later etc (eg. when loading something from the internet null -> person) or object might become null (eq. selectedItemObject -> null)


Notes:

In the case of primitives, there is probably no way to optimize other than isEqual = a === b which seems fine for me for primitives.

Support for primitives is rather a consistent interface API when working with proxyequal