formik icon indicating copy to clipboard operation
formik copied to clipboard

useFormik in React Native

Open nephix opened this issue 2 years ago • 2 comments

Bug report

Current Behavior

const { handleSubmit } = useFormik({
  initialValues: { foo: 'bar' },
  onSubmit: (values) => console.log(values),
});

The signature of handleSubmit is:

handleSubmit: (e?: React.FormEvent<HTMLFormElement> | undefined) => void;

Expected behavior

The signature of onPress of Button from react-native is:

onPress?: ((event: GestureResponderEvent) => void) | undefined;

The documentation says:

Formik is 100% compatible with React Native and React Native Web.

And gives an example using the <Formik> component.

But when using the useFormik hook it results in type conflicts:

error TS2769: No overload matches this call.
  Overload 1 of 2, '(props: ButtonProps | Readonly<ButtonProps>): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(event: GestureResponderEvent) => void'.
  Overload 2 of 2, '(props: ButtonProps, context: any): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(event: GestureResponderEvent) => void'.

134         onPress={handleSubmit}
            ~~~~~~~

  ../../node_modules/@types/react-native/index.d.ts:5145:5
    5145     onPress?: ((event: GestureResponderEvent) => void) | undefined;
             ~~~~~~~
    The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'
  ../../node_modules/@types/react-native/index.d.ts:5145:5
    5145     onPress?: ((event: GestureResponderEvent) => void) | undefined;
             ~~~~~~~
    The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps>'

Reproducible example

import type { FC } from "react";
import { Button } from "react-native";
import { useFormik } from "formik";

export const Test: FC = () => {
  const { handleSubmit } = useFormik({
    initialValues: { foo: "bar" },
    onSubmit: (values) => console.log(values),
  });

  return <Button onPress={handleSubmit} />;
};

Your environment

Software Version(s)
Formik ^2.2.9
React 18.1.0
TypeScript ^4.6.3
Browser ---
npm/Yarn 8.19.2
Operating System macOS

nephix avatar Nov 29 '22 19:11 nephix

I'm facing the same issue. Hope someone could propose a solution!

huuphat1908 avatar Dec 08 '22 07:12 huuphat1908

As a workaround its possible to do some type manipulation with handleSubmit in onPress. Casting to an unknown and then to (e: GestureResponderEvent) => void resolves the type error. Not the best solution but thats the easiest workaround Ive been able to find so far

onPress={
    handleSubmit as unknown as (e: GestureResponderEvent) => void 
}

m-alexeev avatar Oct 11 '23 21:10 m-alexeev