0

I am using XState as a state manager for a website I build in Nuxt 3. Upon loading some states I am using some asynchronous functions outside of the state manager. This looks something like this:

import { createMachine, assign } from "xstate"

// async function
async function fetchData() {
    const result = await otherThings()
    return result
}

export const myMachine = createMachine({
    id : 'machine',
    initial: 'loading',
    states: {
        loading: {
            invoke: {
                src: async () =>
                {
                    const result = await fetchData()
                    
                    return new Promise((resolve,  reject) => {
                        if(account != undefined){
                            resolve('account connected')
                        }else {
                            reject('no account connected')
                        }
                    })
                },
                onDone: [ target: 'otherState' ],
                onError: [ target: 'loading' ]
            }
        }
        // more stuff ...
    }
})

I want to use this state machine over multiple components in Nuxt 3. So I declared it in the index page and then passed the state to the other components to work with it. Like this:

<template>
    <OtherStuff :state="state" :send="send"/>
</template>

<script>
    import { myMachine } from './states'
    import { useMachine } from "@xstate/vue"  

    export default {
        setup(){
            const { state, send } = useMachine(myMachine)
            
            return {state, send}
        }
    }
</script>

And this worked fine in the beginning. But now that I have added asynchronous functions I ran into the following problem. The states in the different components get out of sync. While they are progressing as intended in the index page (going from 'loading' to 'otherState') they just get stuck in 'loading' in the other component. And not in a loop, they simply do not progress.

How can I make sure that the states are synced in all my components?

rajohs
  • 237
  • 1
  • 6

0 Answers0