DEV Community

Discussion on: Replacing Vuex with XState

Collapse
 
danroc profile image
Daniel da Rocha

I was actually trying to use apollo to fetch data in my machines and for that I needed to reference the app somehow. So I figured I'd do it within a plugin file, so that I could access app:

// fetchMachine plugin
const fetchMachine = (app) => {
  return Machine({
      // ...
  })
}

export default ({ app }, inject) => {
  inject('fetchMachine', fetchMachine(app))
}
// my-component.vue
<script>
import { interpret } from 'xstate'
export default {
  data() {
    return {
      fetchService: interpret(this.$fetchMachine),
      current: this.$fetchMachine.initialState
    }
  },
  // ...
  created() {
    this.fetchService.onTransition((state) => (this.current = state)).start()
  },
  methods: {
    send(event) {
      this.fetchService.send(event)
    },
    matches(value) {
      return this.current.matches(value)
    }
  }
}

The component part above is taken from the xstate docs, the Vue implementation of their reddit API machine.

But this is very specific to one machine, and that's why I like your method because I can create machines on the fly as needed...

Thread Thread
 
felix profile image
Felix Guerin

I hadn't seen that. I'll definitely look at it. Making the machines available throughout the whole app as plugins is a really good idea. No need to import it every time.

Thread Thread
 
felix profile image
Felix Guerin

Hey Daniel, I just published a Vue plugin to facilitate the setup outlined in the post. The link is in the edit at the end if you're interested!

Thread Thread
 
danroc profile image
Daniel da Rocha

that's really cool Felix! It makes life easier and hopefully inspires othe people to try xstate and fsm in their projects!