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

feat: Added ability to provide patching function to setStatus method #3931

Open
wants to merge 2 commits 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
2 changes: 1 addition & 1 deletion docs/api/formik.md
Expand Up @@ -200,7 +200,7 @@ Set the value of a field imperatively. `field` should match the key of

If `validateOnChange` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

#### `setStatus: (status?: any) => void`
#### `setStatus: (status?: React.SetStateAction<any>) => void`

Set a top-level `status` to anything you want imperatively. Useful for
controlling arbitrary top-level state related to your form. For example, you can
Expand Down
7 changes: 4 additions & 3 deletions packages/formik/src/Formik.tsx
Expand Up @@ -728,9 +728,10 @@ export function useFormik<Values extends FormikValues = FormikValues>({
[]
);

const setStatus = React.useCallback((status: any) => {
dispatch({ type: 'SET_STATUS', payload: status });
}, []);
const setStatus = React.useCallback((status: React.SetStateAction<any>) => {
const resolvedStatus = isFunction(status) ? status(state.status) : status;
dispatch({ type: 'SET_STATUS', payload: resolvedStatus });
}, []);

const setSubmitting = React.useCallback((isSubmitting: boolean) => {
dispatch({ type: 'SET_ISSUBMITTING', payload: isSubmitting });
Expand Down
2 changes: 1 addition & 1 deletion packages/formik/src/types.tsx
Expand Up @@ -77,7 +77,7 @@ export interface FormikComputedProps<Values> {
*/
export interface FormikHelpers<Values> {
/** Manually set top level status. */
setStatus: (status?: any) => void;
setStatus: (status?: React.SetStateAction<any>) => void;
/** Manually set errors object */
setErrors: (errors: FormikErrors<Values>) => void;
/** Manually set isSubmitting */
Expand Down
14 changes: 14 additions & 0 deletions packages/formik/test/Formik.test.tsx
Expand Up @@ -829,6 +829,20 @@ describe('<Formik>', () => {

expect(getProps().status).toEqual(status);
});

it('setStatus takes a function which can patch status', () => {
const initialStatus = { name: 'sam' };
const { getProps } = renderFormik({ initialStatus: initialStatus });

act(() => {
getProps().setStatus((status: typeof initialStatus) => ({
...status,
age: 80,
}));
});
expect(getProps().status.name).toEqual('sam');
expect(getProps().status.age).toEqual(80);
});
});
});

Expand Down