thefrontside/microstates

from() examples with objects don't work

EvgenyOrekhov opened this issue · 5 comments

const { from } = require("microstates");

from({ a: { b: { c: 42 } } }).a.b.c.increment().state;

TypeError: Cannot read property 'b' of undefined

RunKit: https://runkit.com/5dc54f28f791bc00137208a3/5dc54f28d0ba090013cdbcee

This example with create() also fails:

const { create } = require("microstates");

create(Object, { a: 123 }).a.increment().state;

TypeError: Cannot read property 'increment' of undefined

Am I doing it wrong? I just stumbled upon this library, and I'm reading the docs and trying it in RunKit. In my understanding this should work, but it doesn't.

Hi @EvgenyOrekhov! Oh no! I'm sorry that they didn't work for you. It looks like the documentation has become outdated.

In the beginning, you could actually access keys directly off of microstates for both Objects and Arrays

However, when we refactored the architecture to become completely lazy the keyed access had to go since it required eager evaluation (without the use of Proxy which is still not present on platforms we want to support and cannot be shimmed)

We later removed keyed access to objects for similar reasons. And we at least updated the documentation in a few places, but it looks like we missed some. Thank you for taking the time to report this and not just bouncing!

As a follow up, the following is how you would accomplish those examples:

https://runkit.com/cowboyd/5dc5bbc24915240015211a1e

Another thing to note is that only primitive microstates have the state parameter. To get the value of a microstate you can use the valueOf function from the microstates package.

The create example would look like:

const { create } = require("microstates");

valueOf(create(Object, { a: 123 }).entries.a.entries.increment());

It can seem awkward that you have to use the entries keyword, but most of the time entries is useful in a demo like this one, but in application code, you won't be actually accessing the entries of an object by hand, instead you'll be iterating over them programatically..

@cowboyd Your RunKit example got broken, but thanks anyway! Looking forward to documentation updates!

Oops. I had some accidental garbage in there. Should be working now....