简体   繁体   中英

React multistep form with SessionStorage

I'm newish to React and have a multi step profile creation form. I've looked for a best use case for sessionStorage, but no one seems very passionate one way or the other. Currently I have the form being a main component:

render() {
switch (this.state.step) {
  case 2:
    return <Step nextStep={this.nextStep} prevStep={this.prevStep} /.
  case 3:
    return <Step nextStep={this.nextStep} prevStep={this.prevStep} />
  case 4:
    return <Step nextStep={this.nextStep} prevStep={this.prevStep} />
  case 5:
    return <Step nextStep={this.nextStep} prevStep={this.prevStep} />
  default:
    return <Step nextStep={this.nextStep} />
}
}

Each of these steps has multiple input fields and I was wondering if it was bad practice to store these values in sessionStorage in their component (or localstorage) rather than state or a redux Store and send them to the backend once all the fields have been collected.

Let's talk about order process as this is what I am doing in a project at the moment. Order process consists from steps with multiple forms.

  • Whole Order state is stored somewhere (be it state in parent components, redux store, local storage, or combination of those).
  • every step/form itself update only related portion of Order state - portion which form is interested in.
  • on form submit, there is mechanism which validates form and allow, or disallows transition to next step (more on this bellow)

Transition from step A to B (or B to C, or any other) is managed with Finite State Machine. It holds current Order state (which tell what form should be rendered), definitions of steps and state transition across steps.

On transition attempt there is hooked invoked, if registered. Result of hook signals whether state machine should allow transition and update Order state. Hooks can be sync, or async as well...

Well, that's theory.

Finite State Machine of my choice https://github.com/jakesgordon/javascript-state-machine/tree/v3

Implementation is tied to project.

It depends. I'd say you need a very specific reason for saving it in session or local storage. That reason could be, that you need the form fields to persist, even if the user refreshes the page.

You can still use Redux along with local storage. You just use your local storage, to initialize the Redux state, and update the local storage using Redux actions.

So if you start with Redux, you can always add session- local storage later, if you decide you really need the inputs to be persistent between sessions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM