Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Solve , Hooks can only be called inside of the body of a function component

I’m trying to dispatch a login function from a component.
But this error on submit

Warning: An unhandled error was caught from submitForm() Error:
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)

Here are the versions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 "react-dom": "^17.0.2",

 "react": "^17.0.2",
  1. You might be breaking the Rules of Hooks
  2. You might have more than one copy of React in the same app

I’m using only one app.

I have been using this approach in other projects similarly, but this time it is not working,
Please help me to eliminate this issue.
That is the related code.

export default function LoginForm() {
  const dispatch = useDispatch;
  const navigate = useNavigate();

  const userLogin = useSelector((state) => state.userLogin);
  const { error: loginError, loading: loginLoading, userInfo } = userLogin;

  const [showPassword, setShowPassword] = useState(false);

  const LoginSchema = Yup.object().shape({
    email: Yup.string().email('Email must be a valid email address').required('Email is required'),
    password: Yup.string().required('Password is required'),
  });

  const formik = useFormik({
    initialValues: {
      email: '',
      password: '',
    },
    validationSchema: LoginSchema,
    onSubmit: () => {
      dispatch(login(values.email, values.password));
    },
  });

  const { errors, touched, values, isSubmitting, handleSubmit, getFieldProps } = formik;

  const handleShowPassword = () => {
    setShowPassword((show) => !show);
  };

  useEffect(() => {
    if (userInfo) {
      navigate('/dashboard', { replace: true });
    }
  }, [navigate, userInfo]);

>Solution :

You’re assigning the useDispatch function to dispatch const

const dispatch = useDispatch;

instead of calling the hook to get the actual dispatch function

const dispatch = useDispatch();

That’s why you’re getting the error later when calling the dispatch.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading