Skip to content

Commit

Permalink
refactor(react): improve form-spy (#824)
Browse files Browse the repository at this point in the history
  • Loading branch information
janryWang authored Apr 27, 2020
1 parent 06c1a31 commit c4dc214
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
17 changes: 12 additions & 5 deletions packages/react/src/__tests__/spy.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,19 +104,25 @@ describe('useFormSpy hook', () => {
const opts = {}
const form = createForm(opts)
const actions = createFormActions()
const { getByTestId, queryByTestId } = render(
const { getByTestId, queryByTestId, baseElement } = render(
<Form form={form} actions={actions}>
<InputField name="a" required />
<FormSpy
selector={[LifeCycleTypes.ON_FIELD_VALUE_CHANGE]}
reducer={state => {
reducer={(state, { payload }) => {
return {
count: (state.count || 0) + 1
count: (state.count || 0) + 1,
value: payload.value
}
}}
>
{({ state }) => {
return <div data-testid="spy-value">{state.count}</div>
return (
<div>
<div data-testid="spy-value">{state.value}</div>
<div data-testid="spy-count">{state.count}</div>
</div>
)
}}
</FormSpy>
</Form>
Expand All @@ -129,6 +135,7 @@ describe('useFormSpy hook', () => {
fireEvent.change(queryByTestId('test-input'), { target: { value: 789 } })
})
await wait()
expect(getByTestId('spy-value').textContent).toEqual('3')
expect(getByTestId('spy-value').textContent).toEqual('789')
expect(getByTestId('spy-count').textContent).toEqual('1')
})
})
4 changes: 3 additions & 1 deletion packages/react/src/hooks/useFormSpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const useFormSpy = (props: IFormSpyProps): ISpyHook => {
const form = useContext(FormContext)
const initializedRef = useRef(false)
const unmountRef = useRef(false)
const timerRef = useRef({})
const subscriberId = useRef<number>()
const [type, setType] = useState<string>(LifeCycleTypes.ON_FORM_INIT)
const [state, dispatch] = useReducer(
Expand All @@ -25,7 +26,8 @@ export const useFormSpy = (props: IFormSpyProps): ISpyHook => {
)
const subscriber = useCallback<FormHeartSubscriber>(({ type, payload }) => {
if (initializedRef.current) return
setTimeout(() => {
clearTimeout(timerRef.current[type])
timerRef.current[type] = setTimeout(() => {
if (unmountRef.current) return
payload = payload && isFn(payload.getState) ? payload.getState() : payload
if (isStr(props.selector) && FormPath.parse(props.selector).match(type)) {
Expand Down

0 comments on commit c4dc214

Please sign in to comment.