0

I'm trying to show a component and hide another based on a click event. However, I'm getting this error saying there is an infinite loop.

this is my code

 const { register, handleSubmit, formState: { errors } } = useForm();

 const [showPage , setShowPage] = useState(true);

 {showPage &&(
        <div>
      <FormContent>
        <Form 
              onSubmit={
                handleSubmit((data, e) => {
                try {
                  console.log(data);
                  setShowPage(false);
                  e.preventDefault();
                  //submit(data); 
                } catch (err) {
              console.log(err);
            }
        })}>
        </Form>
      </FormContent>
      </div>
      )}
      {!showPage &&(
        <ForthPage />
      )}

and this is the error i'm getting

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

  49 | onSubmit={handleSubmit((data, e) => {
  50 |   try {
  51 |     console.log(data);
> 52 |     setShowPage(false);
     | ^  53 |     e.preventDefault();
  54 |     //submit(data); 
  55 |   } catch (err) {

Can anyone explain what is wrong with my code

2
  • Post the full component Commented Oct 29, 2022 at 11:23
  • Post the full component, and what is submit() referring to?, handleSubmit should be a callBack function., and showPage ? <A/>:<B/> should do the job. Commented Oct 29, 2022 at 11:49

1 Answer 1

2
onSubmit={()=>{
    handleSubmit((data, e) => {
        try {
            console.log(data);
            setShowPage(false);
            e.preventDefault();
            //submit(data); 
        } catch (err) {
            console.log(err);
        }
        })
    }
}

If you want to call function or execution in onSubmit or any onClick function, you should use arrow function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.