davestewart / javascript-state-machine

An expressive, feature-rich, event-driven JavaScript finite-state machine
http://statemachine.davestewart.io
343 stars 25 forks source link

How to use this for backend rendering #22

Closed ravjsdev closed 6 years ago

ravjsdev commented 6 years ago

Hi @davestewart,

I really like this project and would like to use it for server side rendering (expressjs) with the rendering logic all handled by the state machine. My app requires sessions and storing each users session and the data they submit across each page. So i guess what i could also do is store the state of the state machine as session data after each request by using StateHelper.object(this.fsm).data - however, how do i instantiate a new StateMachine and reuse the state data I have stored as the new starting point?

Main issue is trying to persist the state machine and the associated state for each session for server side rendering. If you have any ideas that would be great.

thanks

Deva

davestewart commented 6 years ago

Hey Deva,

As I understand it, the same question has been answered in #19 - you just want to serialise and deserialise state, right?

ravjsdev commented 6 years ago

@davestewart Hi, thanks for getting back to me, that's right I want to be able to hydrate the stored state back into a new state machine. So all the data in StateHelper.object(this.fsm).data reinitialises into a new state machine - Im not sure if #19 solves my issue as you are just setting the initial state there?

davestewart commented 6 years ago

Well the "state" of the state machine is really only a string, which references a single node in the transitions config you configure the StateMachine with in the first place:

Config:

var config = {
  transitions: [
    'next : a > b > c',
    'back : a < b < c'
  ]
};

Initial load:

var fsm = setup(new StateMachine(config)).fsm;

Subsequent load:

// set initial state
config.initial = 'b'

// instantiate state machine
var fsm = setup(new StateMachine(config)).fsm;

If you're concerned about the data in the helper, I don't think you need to, as it will just hydrate from the FSM itself!

StateHelper.object(fsm)

Does that make sense?

ravjsdev commented 6 years ago

Yes that makes sense thanks a lot!