import React from 'react' import Spinner from 'react-spinner' import { useAsyncCallback } from '@dawnlabs/tacklebox' import { useAPI } from './ApiContext' import PhotoCredit from './PhotoCredit' function RandomImage(props) { const cacheRef = React.useRef([]) const [cacheIndex, updateIndex] = React.useState(0) const api = useAPI() const [selectImage, { loading: selecting }] = useAsyncCallback(() => { const image = cacheRef.current[cacheIndex] return api.unsplash.download(image.id).then(data => props.onChange({ ...image, ...data })) }) const [updateCache, { loading: updating, error, data: imgs }] = useAsyncCallback( api.unsplash.random ) const needsFetch = !error && !updating && (!imgs || cacheIndex > cacheRef.current.length - 2) React.useEffect(() => { if (needsFetch) { updateCache() } }, [needsFetch, updateCache]) React.useEffect(() => { if (imgs) { cacheRef.current.push(...imgs) } }, [imgs]) const loading = updating || selecting const cache = cacheRef.current const photographer = cache[cacheIndex] && cache[cacheIndex].photographer const bgImage = cache[cacheIndex] && cache[cacheIndex].dataURL return (