statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
27.18k stars 1.26k forks source link

[Feature] Add vue composition API functions #807

Closed studnitz closed 4 years ago

studnitz commented 5 years ago

Bug or feature request?

Feature Request

Description:

I think with the upcoming release of Vue 3.0 and its Composition API which is relatively similar in concept to React Hooks, it would be a great addition to port the current xstate-react Hooks to the Vue Composition API. At the moment the Composition API is backported (with a few caveats), so I could start working on a PR if it's wanted

davidkpiano commented 5 years ago

@studnitz I would love this. What would a Vue hook look like?

Andarist commented 5 years ago

Looking at Vue’s API - it would look exactly the same as existing useMachine 🚀. Only the implementation would differ.

@studnitz is Vue’s setup called once per component’s instance?

studnitz commented 5 years ago

@davidkpiano As @Andarist said. :) @Andarist The documentation says:

setup is called right after the initial props resolution when a component instance is created. Lifecycle-wise, it is called before the beforeCreate hook.

Andarist commented 5 years ago

Thanks for your answer! The last question - is it possible to track current props inside setup? Can't see (looking quickly through it though) any example of this. Are initial props received anyhow there? Can't see any example of receiving them as argument of the setup, nor available at this.

studnitz commented 5 years ago

Yes, that's possible.

Arguments

The function receives the resolved props as its first argument:

export default {
 props: {
   name: String
 },
 setup(props) {
   console.log(props.name)
 }
}

Note this props object is reactive - i.e. it is updated when new props are passed in, and can be observed and reacted upon using the watch function:

AleksejDix commented 4 years ago

I made a first Vue Composition API function today. Was inspired by the react useMachine https://github.com/AleksejDix/vue-use/blob/master/src/compositions/useMachine.js

AleksejDix commented 4 years ago

Yeah I was too late for my PR. @studnitz great work. You are fast.

ChrisShank commented 4 years ago

FYI the alpha for vue@next and @vue/reactivity were released on NPM a couple of days ago.

davidkpiano commented 4 years ago

This was released as @xstate/vue! Currently version 0.1.x