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:
- You might have mismatching versions of React and the renderer (such as React DOM)
Here are the versions
"react-dom": "^17.0.2",
"react": "^17.0.2",
- You might be breaking the Rules of Hooks
- 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]);
CodePudding user response:
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.
CodePudding user response:
You could try useRef
const navigate = useRef(useNavigate());
......
useEffect(() => {
if (userInfo) {
navigate('/dashboard', { replace: true });
}
}, [navigate, userInfo]);