matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Passing Initial Context Via UseMachine (React) Doesn't Seem to Work

cwbuecheler opened this issue · comments

Heya, I have the following code:

  const initialContext = { isUpgradeNeeded: true };
  const [current, send] = useMachine(InitializeMachine, initialContext);

And in my machine file I have the following (this is a somewhat clipped version):

const InitializeMachine = createMachine({
  loadingLocalState: invoke(
    (context) => {
      console.log('initalContext', context);
      return loadLocalState(context)
    },
    transition(
      'done',
      'loadedFromLocal',
      reduce((context, { data }) => {
        return {
          ...context,
          ...data,
        };
      }),
    ),
    transition(
      'error',
      'loadingLocalStateError',
      reduce((context, { error }) => {
        return { ...context, error };
      }),
    ),
  ),
  loadingLocalStateError: final(),
  loadedFromLocal: final(),
});

I was under the impression this should work, because useMachine auto-passes the initial context to createMachine. I've tried making initialContext a function that returns an object, rather than just an object, but that didn't change anything. I feel like I'm missing something very obvious, but I've gone over the docs and can't figure out what it is. Any help would be appreciated!

Forgive me if I missed it, but I didn't see a context object in your machine. In some of the docs, what you refer to as initialContext is sometimes called event. I think the name event was used so not to confuse the event that sets the initial context object with the object itself. You need both...
Take a look at the store.js in the example below. It's not react, but the concept is the same.
https://svelte.dev/repl/a9904c210b474bd2ab71d9b7c26c4c38?version=3.29.4

Note, even though the example demonstrates how to use, useMachine to set initial context, you don't need to. If your good with the starting state of your machine being 'x'. Just set it that way in createMachine. If however, you want you machines starting state to be 'y' by default and 'x' only is this special case, then useMachine is useful in setting that non-default state. Hope that makes sense.

@kayodebristol - Got it, thanks! I didn't realize I needed to define a context object for createMachine - I thought it would get auto-passed from useMachine. Took a look at your code, and I see what I was doing wrong, and everything's working now. Really appreciate the help!