matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Initial State

JustinVoitel opened this issue · comments

maybe there is already a way to do this, but how do I set the initial state for my machine ?
In the first toggle example in the docs(https://thisrobot.life), what to do if I want to start for example at the active state ?
right now it always starts at the first state the machine encounters, which might work in most cases

Hi! Thanks for posting. You are correct that currently it is always in the first listed state. You can change this by extending your machine and changing the current property like so:

const baseMachine = createMachine({
  one: state(),
  two: state()
});

const extendedMachine = Object.create(baseMachine, {
  current: { value: 'two' }
});

Which you can roll into a utility function like so:

const initial = (initialState, machine) => Object.create(machine, {
  current: { value: initialState }
});

const machine = initial('two', createMachine({
  one: state(),
  two: state()
}));

Of course, I'm willing to bring this into Robot if there is a use-case. I couldn't think of why you wouldn't just always like the initial state first. One possible reason I can think of is in order to store the state in between page loads and then restore it later. Is that your use case?

Yea things like restoring or the little example I gave with a toggle component, where the initial state is not always the same might benefit from that.
But I really like your idea with the extended machine :) a little mention in the docs about that might be beneficial for others

I think I'm going to add an optional first argument that is a string of the initial state.

This is now available in 0.2.4. See the docs: https://thisrobot.life/api/createMachine.html#initial