Reputation: 1447
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>
Upvotes: 0
Views: 764
Reputation: 3254
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>
Upvotes: 1