From 782983f70bc1c92fd35cd388bfb6577f5bb5c19b Mon Sep 17 00:00:00 2001 From: Davide Uzzo Date: Thu, 28 Sep 2023 11:34:40 +0200 Subject: [PATCH] Updated useFetchReaderObservableResource adding resource reset action --- src/react/useFetchReaderObservableResource.ts | 5 +++- test/react/react.test.ts | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/react/useFetchReaderObservableResource.ts b/src/react/useFetchReaderObservableResource.ts index c9dc5f4..ac36e2e 100644 --- a/src/react/useFetchReaderObservableResource.ts +++ b/src/react/useFetchReaderObservableResource.ts @@ -18,7 +18,7 @@ export function useFetchReaderObservableResource< notifierTakeUntil?: Observable iniState?: RES.Resource } -): [RES.Resource, (...p: P) => void] { +): [RES.Resource, (...p: P) => void, () => void] { const [value, setValue] = useState>(options?.iniState || RES.init) const [subscriptionRef, subscriptionUnsubscribe] = useSubscriptionRef() @@ -48,5 +48,8 @@ export function useFetchReaderObservableResource< }, [subscriptionRef, subscriptionUnsubscribe] ), + useCallback(() => { + setValue({ _tag: 'init' }) + }, []), ] } diff --git a/test/react/react.test.ts b/test/react/react.test.ts index 1fb894a..c070f90 100644 --- a/test/react/react.test.ts +++ b/test/react/react.test.ts @@ -114,6 +114,34 @@ describe('react', () => { expect(result.current[0]._tag).toBe('done') }) + test('useFetchReaderObservableResource reset', () => { + const ajax = of({ + status: 200, + response: 'hello', + } as AjaxResponse) + + const resource = () => (d: { ajax: typeof ajax }) => + OR.fromAjax(d.ajax, { + 200: t.string.decode, + }) + + const { result } = renderHook(() => MR.useFetchReaderObservableResource(resource, { ajax })) + + expect(result.current[0]._tag).toBe('init') + + act(() => { + result.current[1]() + }) + + expect(result.current[0]._tag).toBe('done') + + act(() => { + result.current[2]() + }) + + expect(result.current[0]._tag).toBe('init') + }) + test('useFetchReaderObservableResource unsubscribe on unMount', async () => { const ajax = of({ status: 200,