-2

I am using react-hook-form for building react multi-step-form. Everything is fine, I am using radio button as my first field in my first step. I have done every thing right, but when I click first time in radio button and click next to go to the second stage, I get null value. If I again click next button, I get the correct value and I reach to the second stage of the form. I am trying hard for days to solve it but not getting the result.

This is my form component:

  <FormProvider {...methods}>
              <form onSubmit={methods.handleSubmit(handleStateClick)}>
                <div >
                  {Stage[currentStage].Comp}
                </div>

                <div >
                  <button ref={postButtonRef} type="submit">
                    {currentStage === 2 ? 'Post' : 'Next'}
                  </button>
                </div>
              </form>
            </FormProvider>

My first stage form comp:

 {Type.map((item, index) => (
          <label key={index} htmlFor={`Type${index}`}>
            <input
              {...register('singleType', { required: true })}
              type="radio"
              id={`Type${index}`}
              value={item}
            />
            <p
              onClick={() => handleTypeClick(index)}
            >
              {item}
            </p>
          </label>
        ))}
const handleStateClick = (data) => {
    console.log(data);
    if (currentStage < listingModelStage.length - 1) {
      setCurrentStage(currentStage + 1);
    }
}

Basically, I am mapping an array

let array=["one","two","three"]

if I click three then I get the data on first click and I move to second stage but, if I click others I get null value on my first next button click, and when I again click the next button I get the data.

Ken White
  • 123,280
  • 14
  • 225
  • 444
All data
  • 1
  • 3

1 Answers1

0

The problem your facing is because useState does not return the changes immediately. This is intended so that the proper data exists on the next component lifecycle.

Solution (useRef):

//your code...
const currentStageRef = useRef(0)

const handleStateClick = (data) => {
    if (currentStageRef.current < listingModelStage.length - 1) {
      currentStageRef.current += 1
    }
}

This will give you the updated data immediately, because it has no effect on the component lifecycle.

Arcanus
  • 642
  • 5
  • 20