-
Notifications
You must be signed in to change notification settings - Fork 1
/
FormValues.tsx
50 lines (42 loc) · 1.43 KB
/
FormValues.tsx
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
import { isEqual } from "lodash";
import { useContext, useLayoutEffect, useState } from "react";
import { distinctUntilChanged, map, tap } from "rxjs/operators";
import { FormContext } from "./FormContext";
import { IFormContextValue, IFormState, IFormValues, TChildrenRender } from "./interfaces";
import { Subject, Subscription } from "rxjs";
interface IFormValuesInnerProps {
formValues: IFormValues;
updateFormValues: IFormContextValue["updateFormValues"];
}
interface IFormValuesProps {
children: TChildrenRender<IFormValuesInnerProps>;
}
export function FormValues(props: IFormValuesProps) {
const { updateFormValues, getFormValues, subscribe } = useContext(FormContext);
const defaultFormValues = getFormValues() as IFormValues;
const [formValues, setFormValues] = useState(defaultFormValues);
useLayoutEffect(() => {
let subscription: Subscription | null = null;
const formStateObserver$ = new Subject<IFormState>();
formStateObserver$
.pipe(
map((formState: IFormState) => ({
...formState.values,
})),
distinctUntilChanged(isEqual),
tap((values: IFormValues) => setFormValues(values)),
)
.subscribe();
subscription = subscribe(formStateObserver$);
return () => {
if (subscription) {
subscription.unsubscribe();
subscription = null;
}
};
}, []);
return props.children({
formValues,
updateFormValues,
});
}