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 52 53 | 4x 4x 4x 4x 4x 4x 4x 4x 12x 12x 12x 11x 11x 11x 12x 12x 12x | import React from 'react';
import useSWR from 'swr';
import { useRouter } from 'next/router';
import createFetcher from '@/helpers/createFetcher';
import { analyticsSchema } from '../types/schemas';
import type { AnalyticsData } from '../types/api';
const initialValues: AnalyticsData = {
pageViews: 0,
newUsers: 0,
};
/**
* SDD-L07: `error` was declared `boolean` here and in every sibling hook. SWR types its response as
* `SWRResponse<Data, Error>` with `Error` defaulting to `any` when only the first generic is given,
* and `any` assigns to `boolean` without complaint. So the declaration said boolean, an `Error`
* object flowed, and every widget could show only one undifferentiated error icon — a boolean cannot
* express anything else.
*/
type ReturnType = {
data: AnalyticsData;
error: Error | undefined;
loading: boolean;
};
const fetchAnalytics = createFetcher(analyticsSchema, '/api/analytics');
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, Error>(memoUrl, fetchAnalytics, {
keepPreviousData: all ? true : false,
fallback: initialValues,
fallbackData: initialValues,
dedupingInterval: 5000,
});
return {
data: data ?? initialValues,
error,
loading: isLoading,
};
};
export default useAnalytics;
|