Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help to Identify which button is clicked when the user has multiple s… #3859

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 12 additions & 3 deletions packages/formik/src/Formik.tsx
Expand Up @@ -4,6 +4,7 @@ import * as React from 'react';
import isEqual from 'react-fast-compare';
import invariant from 'tiny-warning';
import { FieldConfig } from './Field';

import { FormikProvider } from './FormikContext';
import {
FieldHelperProps,
Expand Down Expand Up @@ -150,6 +151,7 @@ export function useFormik<Values extends FormikValues = FormikValues>({
const initialErrors = React.useRef(props.initialErrors || emptyErrors);
const initialTouched = React.useRef(props.initialTouched || emptyTouched);
const initialStatus = React.useRef(props.initialStatus);
const extraArgsOnSubmit=React.useRef(undefined);
const isMounted = React.useRef<boolean>(false);
const fieldRegistry = React.useRef<FieldRegistry>({});
if (__DEV__) {
Expand Down Expand Up @@ -801,8 +803,15 @@ export function useFormik<Values extends FormikValues = FormikValues>({
);
});

const handleSubmit = useEventCallback(
(e?: React.FormEvent<HTMLFormElement>) => {
const handleSubmit = useEventCallback(function
(e?: React.FormEvent<HTMLFormElement> | any ,extraArgs?: any) {

extraArgsOnSubmit.current=extraArgs;
Copy link
Collaborator

@quantizor quantizor Sep 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we just passed the event itself when available and let the consumer decide what they want to do with it?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First of all, I was thinking the same. But this would bind the user to call the handleSubmit on the Submit Button. What if the user wants to directly call the handleSubmit then I think the above-implemented strategy would work fine.

One more think if we pass the event it would make it more cumbersome for user to deal with the nativeEvent instead deal with a string/object.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@probablyup a soft reminder.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@probablyup a soft reminder.


if(!(e && e.preventDefault)){
extraArgsOnSubmit.current=e as any;
}

if (e && e.preventDefault && isFunction(e.preventDefault)) {
e.preventDefault();
}
Expand Down Expand Up @@ -856,7 +865,7 @@ export function useFormik<Values extends FormikValues = FormikValues>({
};

const executeSubmit = useEventCallback(() => {
return onSubmit(state.values, imperativeMethods);
return onSubmit(state.values, imperativeMethods,extraArgsOnSubmit?.current);
});

const handleReset = useEventCallback(e => {
Expand Down
5 changes: 3 additions & 2 deletions packages/formik/src/types.tsx
Expand Up @@ -128,7 +128,7 @@ export interface FormikHelpers<Values> {
*/
export interface FormikHandlers {
/** Form submit handler */
handleSubmit: (e?: React.FormEvent<HTMLFormElement>) => void;
handleSubmit: (e?: React.FormEvent<HTMLFormElement> | any, extraArgs?: any) => void;
/** Reset form event handler */
handleReset: (e?: React.SyntheticEvent<any>) => void;
handleBlur: {
Expand Down Expand Up @@ -221,7 +221,8 @@ export interface FormikConfig<Values> extends FormikSharedConfig {
*/
onSubmit: (
values: Values,
formikHelpers: FormikHelpers<Values>
formikHelpers: FormikHelpers<Values>,
extraArgs: any
) => void | Promise<any>;
/**
* A Yup Schema or a function that returns a Yup schema
Expand Down
84 changes: 84 additions & 0 deletions packages/formik/test/Formik.test.tsx
Expand Up @@ -440,6 +440,90 @@ describe('<Formik>', () => {
fireEvent.click(screen.getByTestId('submit-button'));
}).not.toThrow();
});
it('should call onSubmit with the extra argument as the 3rd argument, By Pass the extra argument as second argument of handleSubmit',async () => {
const onSubmitMock = jest.fn();

const FormWithArgument = (
<Formik initialValues={{ name: 'jared' }} onSubmit={ onSubmitMock}>
{({ handleSubmit }) => (
<form onSubmit={(event) =>{handleSubmit(event ,"extra-arg")}}>
<button
data-testid="submit-button"
type='submit'
/>
</form>
)}
</Formik>
);

render(FormWithArgument);
act(()=>{

fireEvent.click(screen.getByTestId('submit-button'));
})


await waitFor(()=>{

expect(onSubmitMock).toHaveBeenCalledWith(
{ name: 'jared' },
expect.objectContaining({
resetForm: expect.any(Function),
setErrors: expect.any(Function),
setFieldError: expect.any(Function),
setFieldTouched: expect.any(Function),
setFieldValue: expect.any(Function),
setStatus: expect.any(Function),
setSubmitting: expect.any(Function),
setTouched: expect.any(Function),
setValues: expect.any(Function),
}),
"extra-arg",
)
});
})

it('should call onSubmit with the extra argument as the 3rd argument.By pass the extra argument as first argument of handleSubmit',async () => {
const onSubmitMock = jest.fn();

const FormWithArgument = (
<Formik initialValues={{ name: 'jared' }} onSubmit={ onSubmitMock}>
{({ handleSubmit }) => (
<button
data-testid="submit-button"
onClick={() =>{handleSubmit("event")}}
/>
)}
</Formik>
);

render(FormWithArgument);
act(()=>{

fireEvent.click(screen.getByTestId('submit-button'));
})


await waitFor(()=>{

expect(onSubmitMock).toHaveBeenCalledWith(
{ name: 'jared' },
expect.objectContaining({
resetForm: expect.any(Function),
setErrors: expect.any(Function),
setFieldError: expect.any(Function),
setFieldTouched: expect.any(Function),
setFieldValue: expect.any(Function),
setStatus: expect.any(Function),
setSubmitting: expect.any(Function),
setTouched: expect.any(Function),
setValues: expect.any(Function),
}),
"event",
)
});
})


it('should not error if onSubmit throws an error', () => {
const FormNoPreventDefault = (
Expand Down