Skip to content

Commit 89fdaa7

Browse files
committed
fix: Reset state with each new StacAPI instance [fix: #17]
1 parent 09dc339 commit 89fdaa7

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/hooks/useStacSearch.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fetch from 'jest-fetch-mock';
22
import { renderHook, act } from '@testing-library/react-hooks';
33
import useStacSearch from './useStacSearch';
44
import StacApi from '../stac-api';
5+
import { Bbox } from '../types/stac';
56

67
function parseRequestPayload(mockApiCall?: RequestInit) {
78
if (!mockApiCall) {
@@ -391,4 +392,27 @@ describe('useStacSearch', () => {
391392
expect(fetch.mock.calls[1][1]?.method).toEqual('GET');
392393
expect(result.current.results).toEqual({ data: '12345' });
393394
});
395+
396+
it('should reset state with each new StacApi instance', async () => {
397+
const bbox: Bbox = [-0.59, 51.24, 0.30, 51.74];
398+
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
399+
400+
const { result, rerender, waitForNextUpdate } = renderHook(
401+
({ stacApi }) => useStacSearch(stacApi), {
402+
initialProps: { stacApi },
403+
}
404+
);
405+
406+
act(() => result.current.setBbox(bbox));
407+
act(() => result.current.submit());
408+
await waitForNextUpdate();
409+
410+
expect(result.current.results).toEqual({ data: '12345' });
411+
expect(result.current.bbox).toEqual(bbox);
412+
413+
const newStac = new StacApi('https://otherstack.com');
414+
rerender({ stacApi: newStac });
415+
expect(result.current.results).toBeUndefined();
416+
expect(result.current.bbox).toBeUndefined();
417+
});
394418
});

src/hooks/useStacSearch.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useState, useMemo } from 'react';
1+
import { useCallback, useState, useMemo, useEffect } from 'react';
22
import StacApi from '../stac-api';
33
import debounce from '../utils/debounce';
44
import type { ApiError, LoadingState } from '../types';
@@ -42,6 +42,19 @@ function useStacSearch(stacApi: StacApi): StacSearchHook {
4242
const [ nextPageConfig, setNextPageConfig ] = useState<Link>();
4343
const [ previousPageConfig, setPreviousPageConfig ] = useState<Link>();
4444

45+
const reset = () => {
46+
setResults(undefined);
47+
setBbox(undefined);
48+
setCollections(undefined);
49+
setDateRangeFrom('');
50+
setDateRangeTo('');
51+
};
52+
53+
/**
54+
* Reset state when stacApu changes
55+
*/
56+
useEffect(reset, [stacApi]);
57+
4558
/**
4659
* Extracts the pagination config from the the links array of the items response
4760
*/

0 commit comments

Comments
 (0)