I get the following error, not sure what am I doing wrong in instantiating the react hooks inside a arrow functionion:
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)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This is my code snippet: (It's a validation react js file which returns a state of errors if any, and in the calling method it's expecting another state error):
import React, {useState, useEffect} from 'react'; import axios from 'axios';
const [errors, setErrors] = useState({});
const checkUserExists = async (phone) => {
console.log('Inside CheckUserExists')
let isUserExist = false;
let formData = new FormData();
formData.append('phone', phone);
const response = await axios.post('http://localhost:3001/doesUserExistByPhone', formData).then(response=>{
isUserExist = false;
console.log('Success response: ', response)
}).catch(errorResponse=>{
console.log('Error response: ', errorResponse)
isUserExist = true;
setErrors(
...errors, {phone: 'User Already exist, u know?'}
)
})
return isUserExist;
}
const patternName = new RegExp('^[a-zA-Z ]{3,20}$')
const patternPhone = new RegExp('^[0-9]{9,10}$')
const patternEmail = new RegExp('^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$')
const patternPassword = new RegExp('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,})')
if(!values.name || !patternName.test(values.name)){
//errors.name="Please enter a valid name"
}
if(!values.phone || !patternPhone.test(values.phone)){
//errors.phone="Please enter a valid Phone number of 9-10 digits"
}
if(!values.email || !patternEmail.test(values.email)){
//errors.email="Please enter a valid email address"
}
if(!values.password || !patternPassword.test(values.password)){
//errors.password="Please enter a strong password to continue. A strong password has: Atleast 8 characters in length, 2 letters in upper case, 1 special character (!@#$&*), 2 number (0-9), 3 letters in lower case"
}
if(!values.isTermsAndConditionsAccepted){
//errors.isTermsAndConditionsAccepted = "Please Accept the Terms and conditions"
}
//Check if the user already exist
if(values.phone){
console.log('Inside if Values.phone is not NULL... will check if user exist...')
checkUserExists(values.phone)
}
console.log('Errors found before creating user: ', errors);
return {errors};
}
export default ValidateRegister```