Home > OS >  Unable to call react hook inside of Formik handleSubmit
Unable to call react hook inside of Formik handleSubmit

Time:01-25

I am unable to call useDispatch inside of Formik's handleSubmit function. I want to dispatch the submitted form values to the redux store when the submit button is clicked. How can I do this?

Here is the error - An unhandled error was caught from submitForm(), [Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Here are snippets of my code

const handleSubmit = values => {
    const dispatch = useDispatch();
    console.log(dispatch)
    dispatch({
        type: "ADD_TO_PROFILE",
        payload: {...values}
    })
}
<Formik initialValues={{'dob': ''}} 
            onSubmit={handleSubmit}
>
({handleChange, handleBlur, setFieldValue, handleSubmit, values, errors }) => (
 <Button onPress={handleSubmit} />
)}
</Formik>

CodePudding user response:

Move const dispatch = useDispatch(); outside of handleSumbit like this:

const dispatch = useDispatch();
const handleSubmit = values => {
    console.log(dispatch)
    dispatch({
        type: "ADD_TO_PROFILE",
        payload: {...values}
    })
}
<Formik initialValues={{'dob': ''}} 
            onSubmit={handleSubmit}
>
({handleChange, handleBlur, setFieldValue, handleSubmit, values, errors }) => (
 <Button onPress={handleSubmit} />
)}
</Formik>
  •  Tags:  
  • Related