#state machine not initializing correctly with stored state from DB

1 messages · Page 1 of 1 (latest)

open osprey
#

(reposting from #🌠-general )
i have a machine that runs on an HTTP request.
on each request it either provisions from a state stored, or starts from initial state. it transitions to next state, and stores the state back to the DB.

here is the machine transitions:

request 1:

idle
{ getUserName: 'firstName' }
{ getUserName: 'getFirstName' }
(invokes service)

stored state: https://pastebin.com/DsEJpFhj
request 2:

{ getUserName: 'firstName' }
{ getUserName: 'firstName' }
{ getUserName: 'getFirstName' }
(invokes service)

stored state: https://pastebin.com/0kAywZ8w
machine code: https://codesandbox.io/s/condescending-breeze-49kcts

expected on second request is

{ getUserName: 'lastName' }
{ getUserName: 'getLastName' }
CodeSandbox

condescending-breeze-49kcts using parcel-bundler

#

just read other posts, is this related to #1130883856417947710 message ?

#

i updated the code like so:

if (state) {
    const parsed = JSON.parse(state);
    parsed.activities = [];
    s = State.create(parsed); // @ts-ignore
}

same behaviour

#

using XState version 4.37.1

open osprey
#

will try writing something runnable with express later.

shrewd brook
open osprey
#

hmm. That’s gonna result in a big rewrite I reckon 😬

shrewd brook
open osprey
#

it's not stable though :s

#

will interpretedMachine.getSnapshot() output the right state that i can persist?

open osprey
#

what is the correct typescript way to initialize an actor with stored state?

const state: unknown = db.find(id).state;
State.crete(state);
#

i'm not a fan of @ts-ignore

open osprey
open osprey
#

let me find the link

#

some page on xstate docs v4

#

is it maybe referring to unfinished promises?

shrewd brook
#

Ah right, so only machines can be persisted in v4

open osprey
shrewd brook
#

Yes (to the best of my knowledge)

open osprey
#

thanks.

#

what i have opted to do is to waitFor the machine to reach a state tagged with awaiting. however because i am running multiple api requests b/w state transitions i had to increase the timeout on waitFor to 25s (no biggie i guess :D)

#

just added more states + transitions. im on 67 states, 135 transitions. probs need to refactor the machine. someday :P

#

i am taking advantage of assign taking priority. i am using choose and raise to validate incoming events in a single state:

stateA: {
  on: {
    INVALID_INPUT: "handleInvalidInput",
    NEXT_STATE: "stateB",
    EVENT: {
      actions: choose([
        { cond: "failedValidation", actions: raise("INVALID_INPUT"),
        { actions: [assign(...), raise("NEXT_STATE") },
      ]),
    },
  }
}
#

i had a target in stateA but i had to replace it with NEXT_STATE event as the assign in actions[1] of choose was not assigning data and just transitioning to stateB