import { useEffect , useRef } from 'react' ; import { Key , Middleware } from 'swr' ; import { GetGalleriesResponse } from 'hooks/api/galleries/types' ; import { getGalleriesAction } from 'hooks/api/galleries/useGalleries' ; import { getTimeFromISOString } from 'utils/time' ; const ensureLatestGallery = ( useSWRNext ) => ( key , fetcher , config ) => { const swr = useSWRNext ( key , fetcher , config ) ; const isFetchingGallery = Array . isArray ( key ) && key [ 1 ] === getGalleriesAction ; if ( ! isFetchingGallery || ! swr . data ) { return swr ; } const previousData = useRef < GetGalleriesResponse | undefined > ( undefined ) ; const currentTimestamp = getTimeFromISOString ( swr . data . galleries . length > 0 ? swr . data . galleries [ 0 ] . last_updated : 0 ) ; const previousTimestamp = getTimeFromISOString ( previousData . current ?. galleries [ 0 ] ?. last_updated ?? 0 ) ; const serverHasLatestTimestamp = currentTimestamp > previousTimestamp ; useEffect ( ( ) => { if ( serverHasLatestTimestamp ) { previousData . current = swr . data ; } } , [ serverHasLatestTimestamp , swr . data ] ) ; if ( serverHasLatestTimestamp ) { return swr ; } return { ... swr , data : previousData . current , } ; } ; export default ensureLatestGallery ;