Home > front end >  Call of hooks is inside of functional component give error Hooks can only be called inside of the bo
Call of hooks is inside of functional component give error Hooks can only be called inside of the bo

Time:01-06

I have component language for translations

const Language = (props: IOwnProps) => {
    // error is in next line for useSelector 
    const language = useSelector(
        (state: IState) => state.currentLang
    );
    
    return getTranslations(
        props.languageString
    );
};

in form I have validation using formik

const validationSchema = () => {
    const requiredFirstName = Language({
        languageString: firstNameRequired,
    });
    return yup.object({
        firstName: yup
            .string()
            .required(requiredFirstName)
    });
};

here is form component

const UserForm = ({
    userData: userData
    setErrorIndex,
}: UserFormProps) => {
    const formik = useFormik({
        initialValues: {
            userData: userData.firstName,
        },
        validationSchema,
        onSubmit: (values) => {
            const playerDataLocal = {
                firstName: values.firstName,
            };
            handleSubmit(playerDataLocal);
        },
    });

    return (
        <form onSubmit={formik.handleSubmit}>
            <TextField
                id="firstName"
                name="firstName"
                label="First Name *"
                defaultValue={formik.values.firstName}
                onChange={formik.handleChange}
                error={formik.touched.firstName && Boolean(formik.errors.firstName)}
                helperText={formik.touched.firstName && formik.errors.firstName}
                fullWidth
            />
        </form>
    );
};
export default UserForm;

in validation schema line with Language give an error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Call of Language is from validationSchema that is a functional component call stack of error is in line of useSelector from Language call of validationSchema is inside of 'useFormik' can be this the issue? any ideas?

CodePudding user response:

It's because validationSchema is not a React component. You can only use hooks inside of either a functional component or another hook and since validationSchema returns something other than JSX or another component it is not classed as either (see React docs for Hook Rules).

You will probably want to move your hook call up inside UserForm and then pass the result into validationSchema as an argument.

  •  Tags:  
  • Related