| 1 |
import { |
| 2 |
DEFAULT_IMAGE_SEARCH, |
| 3 |
resolveImageSearch, |
| 4 |
} from '@shared/lib/image-search-defaults'; |
| 5 |
import { fetchImages } from '@shared/lib/unsplash'; |
| 6 |
import { useUnsplashCacheStore } from '@shared/state/unsplash-cache'; |
| 7 |
import useSWRImmutable from 'swr/immutable'; |
| 8 |
|
| 9 |
const searchImages = async (search, source = null) => { |
| 10 |
const cache = useUnsplashCacheStore.getState(); |
| 11 |
if ( |
| 12 |
search === DEFAULT_IMAGE_SEARCH && |
| 13 |
!cache.isEmpty() && |
| 14 |
!cache.hasExpired() |
| 15 |
) { |
| 16 |
return cache.images; |
| 17 |
} |
| 18 |
return await fetchImages(resolveImageSearch(search), source); |
| 19 |
}; |
| 20 |
|
| 21 |
export const useUnsplashImages = (search, source = null) => { |
| 22 |
const key = search || DEFAULT_IMAGE_SEARCH; |
| 23 |
const { data, error } = useSWRImmutable(key, () => searchImages(key, source)); |
| 24 |
return { data, error, loading: !data && !error }; |
| 25 |
}; |
| 26 |
|