matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

initialContext is not set

BenjaminBrossi opened this issue · comments

Seems like i cant provide an inital context with the useMachine-hook:

const states = {
  loading: invoke<Context, QuizPublic | undefined>(
    async (...context) => {
      console.log('Context', context);
      return undefined; //getQuiz(context.language, context.quizId);
    },
    transition(
      'done',
      'loaded',
      reduce((context: Context, { data }: Event<QuizPublic>) => {
        console.log(data);
        return { ...context, quiz: data };
      })
    )
  ),
  loaded: state(
    immediate(
      'intro',
      guard((...args) => {
        console.log('Guard', args);
        return true;
      })
    ),
    immediate('')
  ),
  intro: state(),
};

export const quizMachine = createMachine<typeof states, Context>('loading', states);
const [current, send] = useMachine(quizMachine, { ...defaultContext(), quizId, language });

I know this issue is stale but I ran into this just now and maybe it helps the next person. It seems as a workaround you can explicitly pass a pass-through context fn as the last argument to createMachine because it otherwise defaults to () => {}.

const quizMachine = createMachine('loading', states, (initialContext) => initialContext);
const [current, send] = useMachine(quizMachine, { ...defaultContext(), quizId, language });

Likely a bug and not by design but I'm still wrapping my head around the code.