Home > Back-end >  React Native & Formik pass custom params to onSubmit
React Native & Formik pass custom params to onSubmit

Time:12-30

I'm using Formik to submit my forms. I'm trying to add a custom params to my onSubmit function, so that I can get values of the form and that custom parameter.

const handleSubmit = async (customParam) => {
    console.log(customParam);
    console.log('Values : ');
    console.log(values);
}


<AppForm initialValues={{ rejectionComment: "" }} onSubmit={handleSubmit(myCustomParam)}> //My FORMIK form
    <AppFormField multiline={true} numberOfLines={4} name="rejectionComment" secured={false} autoCapitalize="none" autoCorrect={false}/>
    <SubmitButton title="Valider" /> //Validation button
</AppForm>

With this code, i'm able log the myCustomParam but I cannot get the values of the form [Unhandled promise rejection: ReferenceError: values is not defined]

If I change onSubmit to onSubmit={handleSubmit} and handleSubmit to const handleSubmit = async (values) => {console.log(values);} i can log my values, but cannot add my custom param.

Can you please provide some help ?

CodePudding user response:

Abe pointed the obvious. By using the callback, i've been able to define both values and custom params :

onSubmit={(values) => handleSubmit(values, "test")}

const handleSubmit = async (values, customParam) => {
    console.log(values);
    console.log(customParam);
}

CodePudding user response:

You can do this with two changes.

  1. Change your handleSubmit function to accept two arguments (it also doesn't need to be async, unless you're doing more things than you have shown here).
const handleSubmit = (values, customParam) => {
  console.log({ values, customParam });
};
  1. Pass values where Formik provides them.
<AppForm
  onSubmit={values => { handleSubmit(values, myCustomParam); })}
  ...
>

Explanation:

When you change your code to onSubmit={handleSubmit), the Formik component calls it with the form values. The long form of this would be onSubmit={values => handleSubmit(values)}. Since your custom param is defined outside of Formik, you need to pass it in to the function manually.

  • Related