devrnt / react-use-wizard

🧙 A React wizard (stepper) builder without the hassle, powered by hooks.

Home Page:https://devrnt.github.io/react-use-wizard/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The step handler is not cleared on a transition to the previous step

adelvalvisma opened this issue · comments

If a step runs handleStep to set a callback to be called when calling nextStep, this callback also executes in a previous step if the user goes backward n steps and then goes forward at some point. For example:

<Wizard>
  <Step 1 />  {/* does not call handleStep */} 
  <Step 2 />  {/* calls handleStep(() => console.log("going to step 3")) */}
  <Step 3 />  {/* does not call handleStep */} 
</Wizard>

step 1 -> step 2 (prints "going to step 3") -> step 3 (OK)
step 1 -> step 2 -> step 1 (prints "going to step 3") -> step 2 -> step 3 (KO)

The reason is the callback is only cleared during a next step transition:

const doNextStep = React.useRef(async () => {
  if (hasNextStep.current && nextStepHandler.current) {
    try {
      setIsLoading(true);
      await nextStepHandler.current();
      setIsLoading(false);
      nextStepHandler.current = null; // here
      goToNextStep.current();
    } catch (error) {
      setIsLoading(false);
      throw error;
    }
  } else {
    goToNextStep.current();
  }
});

const goToPreviousStep = React.useRef(() => {
  if (hasPreviousStep.current) {
    setActiveStep((activeStep) => activeStep - 1);
  }
});

Hi thanks for creating this issue. This is indeed not expected, I guess you're using the goToStep method to go back? Can you provide a codesandbox, just to make sure we're pointing to the same issue?

Anyway, at first sight clearing the "nextStepHandler" in the goToStep the will solve this.

Hi, thanks for your quick response @devrnt.

Check out this: https://codesandbox.io/s/trusting-mahavira-hkrk7. As you can see both previousStep and goToStep methods are failing.