kenkunz / svelte-fsm

Tiny, expressive finite state machines for svelte
MIT License
275 stars 9 forks source link

Persisting Object State #11

Closed ghostwalkerj closed 2 years ago

ghostwalkerj commented 2 years ago

I have an JS object that I am serializing and saving the state to a DB store. Do you have and advice on how I could hydrate that object along with the FSM state?

jakubdonovan commented 2 years ago

I have an JS object that I am serializing and saving the state to a DB store. Do you have and advice on how I could hydrate that object along with the FSM state?

I subscribed to state so that state is stored in sessionStorage each time state changes. state is a readable store, making it impossible to override its value if sessionStorage key is detected. I would also like to know how to bring the user back to the state they were last in before refresh.

kenkunz commented 2 years ago

I think the simplest approach to this is to have the state machine's initial state something like uninitialized. The sole action in this state is an init method that receives the state you're trying hydrate into. You could validate that the received state matches valid state options before returning the transition state.

Here's a quick REPL example: https://svelte.dev/repl/2b32beadcc0f47e9b49890b7e5034faa?version=3.50.1

Try updating the state with [ next ] / [ previous ], then refresh the page to see that the state machine is re-hydrated to the stored state.

This demo uses sessionStorage, but the same principle would apply if serializing / deserializing from a db.

Note that if you're using SvelteKit or some other framework that supports SSR, you'll need to wrap the hydration in if (browser) {} or onMount() to ensure it only happens in the browser context.

ghostwalkerj commented 2 years ago

Thanks. That's about what I was thinking to do. Appreciate it!