Jackie
Jackie

Reputation: 23607

How do I do a guard in OnDone on XState5?

I am trying to do something like this...

    checkingSession: {
            entry: () => console.log('Entered Checking status state'),
            invoke: {
                src: checkSession,
                input: ({context}) => ({
                    auth0Client: context.auth0Client
                }),
                onDone: [
                    {
                        target: 'authenticated',
                        cond: (_, event) => {
                            console.log(`This user is authenticated ${event.output.isAuthenticated}`);
                            return event.output?.isAuthenticated
                        },
                        actions: ({context, event}) => {
                            console.log("This does work "+event.output.isAuthenticated)
                            context.user = event.output.user;
                            context.isAuthenticated = event.output.isAuthenticated;
                        }
                    },
                    {
                        target: 'notAuthenticated'
                    }
                ],
                onError: {
                    target: 'error',
                    actions: assign({
                        error: (_, event) => event.error?.message || 'Failed to check session'
                    })
                }
            }
    },
    notAuthenticated: {
            entry: () => console.log('Entered notAuthenticated state'),
            on: {
                LOGIN: 'authenticating'
            }
    },
    authenticated: {
            entry: () => console.log('Entered authenticated state'),
            on: {
                LOGOUT: 'loggingOut',
                REFRESH: 'refreshing'
            }
    },
}

The problem is the cond: doesn't seem to work for example the console log says...

Entered Checking status state
index.js:23 Checking session...
index.js:85 This does work false
index.js:130 Entered authenticated state

so how do I do a proper guard in an onDone section?

Upvotes: 0

Views: 54

Answers (1)

customcommander
customcommander

Reputation: 18961

The cond transition property for guarded transitions is now called guard

https://stately.ai/docs/migration#guarded-transitions-use-guard-not-cond

import { createActor, createMachine, fromPromise } from "xstate";

const m = createMachine({
  initial: 'get-answer',
  states: {
    'get-answer': {
      invoke: {
        src: fromPromise(() => 41),
        onDone: [
          {
            guard: ({event}) => event.output === 42,
            target: 'correct-answer',
          },
          {
            target: 'wrong-answer'
          }
        ]
      }
    },
    'correct-answer': {
      type: 'final'
    },
    'wrong-answer': {
      type: 'final'
    }
  }
});

Upvotes: 1

Related Questions