matthewp / robot

🤖 A functional, immutable Finite State Machine library
https://thisrobot.life
BSD 2-Clause "Simplified" License
1.92k stars 88 forks source link

initialContext is not set #193

Open BenjaminBrossi opened 3 years ago

BenjaminBrossi commented 3 years ago

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 });
mcernusca commented 2 years ago

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.