-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFormikPersist.tsx
More file actions
109 lines (95 loc) · 3.36 KB
/
Copy pathFormikPersist.tsx
File metadata and controls
109 lines (95 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { FormikProps, useFormikContext } from 'formik';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import set from 'lodash/set';
import * as React from 'react';
import useIsMounted from '../../../hooks/useIsMounted';
import { isFeatureEnabled } from '../../../utils/featureFlags';
import keyify from '../../../utils/keyify';
// lodash/debounce was problematic in tests so we use our own simple implementation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const debounce = (cb: (...params: any[]) => void, wait: number) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let timeout: any;
return function executedFunction(...args: unknown[]) {
const later = () => {
timeout = null;
cb(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
export interface PersistProps {
name: string;
debounceTime?: number;
isSessionStorage?: boolean;
initialValues: Record<string, unknown>;
// Dot-notation paths of fields that are restored using initial values:
alwaysFreshFields?: string[];
}
const FormikPersist = ({
debounceTime = 300,
isSessionStorage = false,
name,
initialValues,
alwaysFreshFields = [],
}: PersistProps): null => {
const isMounted = useIsMounted();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const formik = useFormikContext<any>();
const debouncedSaveForm = React.useMemo(
() =>
debounce((data: FormikProps<Record<string, unknown>>) => {
/* istanbul ignore next */
if (!isMounted.current) return;
if (isSessionStorage) {
window.sessionStorage.setItem(name, JSON.stringify(data));
} else {
window.localStorage.setItem(name, JSON.stringify(data));
}
}, debounceTime),
[debounceTime, isMounted, isSessionStorage, name]
);
const saveForm = React.useCallback(
(data: FormikProps<Record<string, unknown>>) => {
debouncedSaveForm({ ...data, errors: {} });
},
[debouncedSaveForm]
);
React.useEffect(() => {
if (isFeatureEnabled('FORMIK_PERSIST')) {
saveForm(formik);
}
}, [formik, saveForm]);
React.useEffect(() => {
const storedFormikState = isSessionStorage
? window.sessionStorage.getItem(name)
: window.localStorage.getItem(name);
const storedFormikStateObject =
storedFormikState && JSON.parse(storedFormikState);
if (
storedFormikStateObject &&
objectStructureMatches(initialValues, storedFormikStateObject.values)
) {
const valuesToRestore = cloneDeep(storedFormikStateObject.values);
// Restore fresh fields with their initial values instead of stored ones:
for (const path of alwaysFreshFields) {
set(valuesToRestore, path, get(initialValues, path));
}
formik.setValues(valuesToRestore, true);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
};
const objectStructureMatches = (
a: Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any
b: Record<string, any> // eslint-disable-line @typescript-eslint/no-explicit-any
): boolean => {
const normalizeKeys = (obj: typeof a | typeof b) =>
keyify(obj).sort((s1, s2) => s1.localeCompare(s2));
return isEqual(normalizeKeys(a), normalizeKeys(b));
};
export default FormikPersist;