Building reducers in XState #1563
Replies: 2 comments
-
If we’d like to stick to SCXML semantics - this is not possible. It’s possible to have no states, but it doesnt allow for transition elements - they can only be children of state elements. However, in XState we allow for transitions in the „root” - this kinda means that there is an implicit state already (if we think in SCXML terms) so if we plan to keep this then your use case should be supported. This however means that it would not be possible to convert stateless SCXML document to XState so we could never reach true parity with this spec (unless we ofc try to convert the root node in a different way than the rest - and converting things right now is a very simple mapping between XML and JSON, or unless we provide some other way to achieve this conversion). This is ofc somewhat nitpicky because stateless documents are not really that useful - im commenting mostly the formal aspects & implications of this. |
Beta Was this translation helpful? Give feedback.
-
This can be done somewhat (in userland) with this: #1439 But yeah, what @Andarist is saying is correct - we can accomplish this by having a (perhaps implicit) "default" state, but there has to be at least one state. // tentative API
import { createMachine } from 'xstate';
import { createModel } from 'xstate/lib/model'; // opt-in, not part of main build
// Userland function
function assignersToEvents(model) {
const config = {};
Object.keys(model.assigners).forEach(key => {
config[key] = { actions: model.assigners[key] }
});
return config;
}
const userModel = createModel({
name: 'David',
age: 30
}).withAssigners({
updateName: {
name: (_, e) => e.value
}
});
const machine = createMachine({
initial: 'default',
context: userModel.context,
states: { default: {} }
on: assignersToEvents(userModel)
});
const service = interpret(machine).start();
service.send({ type: 'updateName', value: 'Matt' }); |
Beta Was this translation helpful? Give feedback.
-
I was playing around with XState today and fell into a pattern I thought would naturally work, but didn't.
The Problem: I wanted to write a state machine with zero states, that only handled context assignation and events.
This could have been handled by a reducer, but I also wanted to extend the statechart in future without needing to refactor it.
The roadblock came when I tried to specify a state machine without any states, as in this gist:
https://gist.github.com/mattpocock/213006e692ce6780d6d8bc6c63eda9bf
The state machine could not resolve an initial state, since I didn't pass one in my configuration.
The Solution: I would love it if the machine could resolve a secret initial state here. It would mean I could build very simple pieces of logic in XState which could later be fleshed out into statecharts without any refactoring.
Beta Was this translation helpful? Give feedback.
All reactions