Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finite state machine middleware #70

Closed
universse opened this issue Oct 25, 2019 · 1 comment
Closed

Finite state machine middleware #70

universse opened this issue Oct 25, 2019 · 1 comment

Comments

@universse
Copy link

universse commented Oct 25, 2019

First of all, thanks a lot for this library. I very much enjoy its simplicity.

I'm trying to create a finite state machine middleware based on zustand and would love to seek some feedback. Is there anything I need to look out for in particular?

Here's the implementation.

const defaultUpdater = (state, data) => ({ ...state, ...data })

const machine = (stateChart, initialData, updater = defaultUpdater) => (
  set,
  get,
  api
) => {
  api.transition = (action, data) =>
    set(currentState => {
      const nextState = stateChart.states[currentState.state].on[action]

      return nextState
        ? {
            ...updater(currentState, data),
            state: nextState
          }
        : currentState
    })

  return {
    transition: api.transition,
    state: stateChart.initialState,
    ...initialData
  }
}

And this is example usage.

const IDLE = 'idle'
const ERROR = 'error'
const LOADING = 'loading'

const FETCH = 'fetch'
const FETCH_SUCCESS = 'fetch_success'
const FETCH_ERROR = 'fetch_error'

const stateChart = {
  initialState: IDLE,
  states: {
    [IDLE]: {
      on: {
        [FETCH]: LOADING
      }
    },
    [ERROR]: {
      on: {
        [FETCH]: LOADING
      }
    },
    [LOADING]: {
      on: {
        [FETCH_SUCCESS]: IDLE,
        [FETCH_ERROR]: ERROR
      }
    }
}

const [useStore, { transition }] = create(machine(stateChart, { todos: [] }))

transition(FETCH_SUCCESS, { todos: [...] })
@JeremyRH
Copy link
Contributor

At first look this seems fine. I'd have to use it a bit to give better feedback.

I guess one thing to watch out for is initialData could have properties that overwrite state or transition on the store object.

@JeremyRH JeremyRH closed this as completed May 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants