Xstate: Accept single object instead of multiple args for Machine

Created on 21 Jan 2019  路  4Comments  路  Source: davidkpiano/xstate

Basically a duplicate of https://github.com/carloslfu/use-machine/issues/6 (but I hadn't realized at the time it was following the API here)

When creating a machine with initialContext but no "options" arg it requires passing null/undefined, e.g.

Machine(config, null, initialContext);

I think it would be a bit nicer if Machine instead took an object such that all these are valid:

Machine({config});
Machine({config, options});
Machine({config, initialContext});
Machine({config, options, initialContext});
enhancement invalid

Most helpful comment

Unfortunately, this is probably not a good idea, because actions, services, guards are implementation details, that can change depending on how the statechart is consumed.

A good way to think about this is that config should be able to be a plain JSON object:

const config = require('./someMachine.json');

                    //  馃憞 from JSON
const machine = Machine(config, {/* ... */});

Also, you can already specify initialContext via the context property in config. You can change this by specifying context as the 3rd argument, although I can see that being part of the 2nd argument. If you want that, please open a new issue for that.

All 4 comments

Subjective preference of course, it's not a bug or a feature - feel free to close if it's just not a style you dig

With this in mind it might make sense to bring the different options up a level. In other words:

Machine({config, initialContext, actions, services});
Machine({config, initialContext, actions, guards, services, activities});
//etc.

With typescript it's clear what's required and what's not, but for JS users maybe the ideal is to keep things as they are but just move initialContext to be part of options?

For example:

Machine(config); //same as Machine(config, {})
Machine(config, {initialContext});
Machine(config, {initialContext, services});
Machine(config, {initialContext, actions, services});
//etc.

Unfortunately, this is probably not a good idea, because actions, services, guards are implementation details, that can change depending on how the statechart is consumed.

A good way to think about this is that config should be able to be a plain JSON object:

const config = require('./someMachine.json');

                    //  馃憞 from JSON
const machine = Machine(config, {/* ... */});

Also, you can already specify initialContext via the context property in config. You can change this by specifying context as the 3rd argument, although I can see that being part of the 2nd argument. If you want that, please open a new issue for that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hnordt picture hnordt  路  3Comments

mattiamanzati picture mattiamanzati  路  3Comments

dakom picture dakom  路  3Comments

jfun picture jfun  路  3Comments

bradwoods picture bradwoods  路  3Comments