|
1 | | -import { useState, useEffect} from 'react'; |
| 1 | +import { useState, useEffect, useCallback} from 'react'; |
2 | 2 | import { Item } from '../types/stac'; |
3 | 3 | import { ApiError, LoadingState } from '../types'; |
4 | 4 | import { useStacApiContext } from '../context'; |
5 | 5 |
|
6 | 6 | type ItemHook = { |
7 | | - item?: Item |
8 | | - state: LoadingState |
9 | | - error?: ApiError |
| 7 | + item?: Item; |
| 8 | + state: LoadingState; |
| 9 | + error?: ApiError; |
| 10 | + reload: () => void; |
10 | 11 | } |
11 | 12 |
|
12 | 13 | function useItem(url: string): ItemHook { |
13 | | - const { stacApi, getItem, addItem } = useStacApiContext(); |
| 14 | + const { stacApi, getItem, addItem, deleteItem } = useStacApiContext(); |
14 | 15 | const [ state, setState ] = useState<LoadingState>('IDLE'); |
15 | 16 | const [ item, setItem ] = useState<Item>(); |
16 | 17 | const [ error, setError ] = useState<ApiError>(); |
@@ -38,10 +39,39 @@ function useItem(url: string): ItemHook { |
38 | 39 | .finally(() => setState('IDLE')); |
39 | 40 | }, [stacApi, addItem, getItem, url]); |
40 | 41 |
|
| 42 | + const fetchItem = useCallback(() => { |
| 43 | + if (!stacApi) return; |
| 44 | + |
| 45 | + setState('LOADING'); |
| 46 | + new Promise((resolve, reject) => { |
| 47 | + const i = getItem(url); |
| 48 | + if (i) { |
| 49 | + resolve(i); |
| 50 | + } else { |
| 51 | + stacApi.fetch(url) |
| 52 | + .then(r => r.json()) |
| 53 | + .then(r => { |
| 54 | + addItem(url, r); |
| 55 | + resolve(r); |
| 56 | + }) |
| 57 | + .catch((err) => reject(err)); |
| 58 | + } |
| 59 | + }) |
| 60 | + .then(setItem) |
| 61 | + .catch((err) => setError(err)) |
| 62 | + .finally(() => setState('IDLE')); |
| 63 | + }, [addItem, getItem, stacApi, url]); |
| 64 | + |
| 65 | + const reload = useCallback(() => { |
| 66 | + deleteItem(url); |
| 67 | + fetchItem(); |
| 68 | + }, [deleteItem, fetchItem, url]); |
| 69 | + |
41 | 70 | return { |
42 | 71 | item, |
43 | 72 | state, |
44 | | - error |
| 73 | + error, |
| 74 | + reload |
45 | 75 | }; |
46 | 76 | } |
47 | 77 |
|
|
0 commit comments