import { memo , useCallback , useMemo } from 'react' ; import { SWRConfig } from 'swr' ; import { MINUTE , SECOND } from 'utils/time' ; import useFetcher from './useFetcher' ; import Mixpanel from 'utils/mixpanel' ; import ensureLatestGallery from './middleware/ensureLatestGallery' ; function localStorageProvider ( ) { const map = new Map ( JSON . parse ( localStorage . getItem ( 'app-cache' ) ?? '[]' ) ) ; window . addEventListener ( 'beforeunload' , ( ) => { if ( window . location . pathname === '/nuke' ) { return ; } const arrayMap = Array . from ( map . entries ( ) ) as Array < [ string , any ] > ; const saneArrayMap = arrayMap . filter ( ( arr ) => ! ( arr [ 0 ] . includes ( '$req$' ) || arr [ 0 ] . includes ( '$err$' ) ) ) ; const appCache = JSON . stringify ( saneArrayMap ) ; localStorage . setItem ( 'app-cache' , appCache ) ; } ) ; return map ; } const middleware = [ ensureLatestGallery ] ; export const SwrProvider = memo ( ( { children } ) => { const fetcher = useFetcher ( ) ; const handleLoadingSlow = useCallback ( ( key ) => { Mixpanel . track ( 'Slow request' , { endpoint : key , } ) ; } , [ ] ) ; const value = useMemo ( ( ) => ( { suspense : true , fetcher , provider : localStorageProvider , use : middleware , refreshInterval : 5 * MINUTE , revalidateOnFocus : false , revalidateOnReconnect : true , dedupingInterval : 2 * SECOND , onLoadingSlow : handleLoadingSlow , } ) , [ fetcher , handleLoadingSlow ] ) ; return < SWRConfig value = { value } > { children } < /SWRConfig>; } ) ;