Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 4x 4x 4x 4x 4x 1x 1x 1x 4x 8x 8x 8x 7x 7x 7x 8x 8x 8x | import React from 'react'; import useSWR from 'swr'; import { useRouter } from 'next/router'; import type { AnalyticsData } from '../types/api'; const initialValues: AnalyticsData = { pageViews: 0, newUsers: 0, }; type ReturnType = { data: AnalyticsData; error: boolean; loading: boolean; }; const fetchAnalytics = async (url: string): Promise<AnalyticsData> => { const response = await fetch(url); Iif (!response.ok) { throw new Error(`Failed to fetch analytics data: ${response.statusText}`); } const data = await response.json(); return data as AnalyticsData; }; const useAnalytics = (all?: boolean): ReturnType => { const { asPath, locale } = useRouter(); const slug = locale === 'en' ? asPath : `/${locale}${asPath}`; const memoUrl = React.useMemo(() => { const url = new URL(`${process.env.NEXT_PUBLIC_DOMAIN}/api/analytics`); url.searchParams.set('slug', all ? '' : slug); return url.toString(); }, [all, slug]); const { data, error, isLoading } = useSWR<AnalyticsData>(memoUrl, fetchAnalytics, { keepPreviousData: all ? true : false, fallback: initialValues, fallbackData: initialValues, dedupingInterval: 5000, }); return { data: data ?? initialValues, error, loading: isLoading, }; }; export default useAnalytics; |