Search code examples
react-nativeformikonsubmit

Need formik values in handle submit outside the formik


I have this screen in react native where I want to validate the form and submit it and I have the submit button in my header. How can I get the values in handle submit which is outside the formik. Because I couldn't access the values in the custom function handleSubmit.

React.useLayoutEffect(() => {
            navigation.setOptions({
              headerTitleAlign: 'center',
              headerTitle: () => <Text style={styles.titleHeader}>Payment Method</Text>,
              headerRight: () => (
                <Pressable onPress={handleSubmit}>
                  <Text>Done</Text>
                </Pressable>
              ),
            });
          }, [navigation, userId]);

    const handleSubmit = async (values: any) => {
    const data: any = {
      paymentServiceTypeId: defaultPaymentType,
      invoiceNeeded,
      companyName: company,
      vatNumber,
    }
    console.log(values);
  };
         
    return (
            <Formik
              initialValues={initialState}
              onSubmit={(values) => handleSubmit(values)}
              validationSchema={getValidationSchema(staticValues.static)}
            >
              {({ handleChange, handleBlur, values, touched, errors, setFieldValue }) => (
                <>
        {defaultPaymentType == 2 && (
                    <>
                      <Text style={styles.title}>Company Name</Text>
                      <View style={styles.textInputView}>
                        <TextInput
                          style={styles.inputText}
                          placeholder={'Company Name'}
                          value={values.company}
                          onChangeText={handleChange('company')}
                          onBlur={handleBlur('company')}
                        />
                        {touched.company && errors.company && <Text style= 
                          {styles.errorText}>{errors.company}</Text>}
                    <>
                 )}
               </Formik>
        

Solution

  • This issue can easily be fixed by using useFormik which separates the form from the values and handlers being used by formik. So, even if you have the submit button outside the form, you can use the handleSubmit provided by the Formik.