#XState usage with routers

1 messages · Page 1 of 1 (latest)

drowsy void
#

I'm hoping to leverage XState to be the spine of the logic for a multi-step, onboarding UI. The problems I want XState to solve are:

  • Allow me to create this flow in a way where it's extremely simple to reorder steps in the flow.
  • Try my best to have a bullet-proof UI via state machine enforcing consistent pattern enforcement.
  • Help devs come into an unfamiliar space and have the visual editor to help orient themselves.

The UI is also in a Next.js application and I also want to have each step be a new page file / route.

I see the multi-step form example: https://xstate-catalogue.com/machines/multi-step-form and I found this wonderful example of using React Context providers in Next.js page files to share state globally https://garden.bradwoods.io/notes/javascript/state-management/xstate/global-state - instead of globally, I'd use a layout component, but I think I'm following along.

All that being said, I'm left a bit confused as to how I can code-split the different steps across different page files. One thought I had would be to maintain each step component as a value in a ContextProvider keyed by state names and conditionally render the step based off of the state the machine is in. I can dynamically import each component; however, this strategy wouldn't let me "navigate" between each step via the router since the conditional rendering would happen from one spot.

Maybe I could navigate with path params and have a Next.js dynamic page file conditionally render UI based on the path param; however, this would force me to basically make the flow SSR instead of static on first render and client-side routed afterward.

Would love ideas here!

drowsy void
#

Actually, I think the dynamic page file is the way to go. I can just build all those UIs ahead of time as static pages and redirect a user if they shouldn't see the step they're requesting.

Then, I can just use router.prefetch() on each step's mount + router.push() on each step's submit button click.

The machine itself isn't split, but I think that's negligible.

olive creek
#

I hope you got far with your work, but if it is shareable I would like to have a look. I am in a similar situation on my project.

daring bison
#

I will be making an example of how to work with React-Router and XState this week, by the way

olive creek
#

oooh nice one David thanks!

daring bison
distant charm
#

@daring bison would this work with back/forward browser buttons events?
In my similar setup I had to build a location change listener to capture these events but it's not perfect.