Refactored useQuery functions.

This commit is contained in:
Mike Cao 2023-12-01 20:27:59 -08:00
parent be550cc440
commit b578162cb6
33 changed files with 179 additions and 151 deletions

View File

@ -14,7 +14,10 @@ import styles from './TestConsole.module.css';
export function TestConsole({ websiteId }) {
const { get, useQuery } = useApi();
const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));
const { data, isLoading, error } = useQuery({
queryKey: ['websites:me'],
queryFn: () => get('/me/websites'),
});
const { router } = useNavigation();
function handleChange(value) {

View File

@ -20,9 +20,10 @@ export function Dashboard() {
const { get, useQuery } = useApi();
const { page, handlePageChange } = useApiFilter();
const pageSize = 10;
const { data: result, isLoading } = useQuery(['websites', page, pageSize], () =>
get('/websites', { includeTeams: 1, page, pageSize }),
);
const { data: result, isLoading } = useQuery({
queryKey: ['websites', page, pageSize],
queryFn: () => get('/websites', { includeTeams: 1, page, pageSize }),
});
const { data, count } = result || {};
const hasData = data && data?.length !== 0;

View File

@ -17,7 +17,10 @@ export function DashboardEdit() {
const { formatMessage, labels } = useMessages();
const [order, setOrder] = useState(websiteOrder || []);
const { get, useQuery } = useApi();
const { data: result } = useQuery(['websites'], () => get('/websites', { includeTeams: 1 }));
const { data: result } = useQuery({
queryKey: ['websites'],
queryFn: () => get('/websites', { includeTeams: 1 }),
});
const { data: websites } = result || {};
const ordered = useMemo(() => {

View File

@ -8,9 +8,11 @@ import useCache from 'store/cache';
export default function ReportsDataTable({ websiteId }: { websiteId?: string }) {
const { get } = useApi();
const modified = useCache(state => (state as any)?.reports);
const queryResult = useFilterQuery(['reports', { websiteId, modified }], params =>
get(websiteId ? `/websites/${websiteId}/reports` : `/reports`, params),
);
const queryResult = useFilterQuery({
queryKey: ['reports', { websiteId, modified }],
queryFn: (params: any) =>
get(websiteId ? `/websites/${websiteId}/reports` : `/reports`, params),
});
return (
<DataTable queryResult={queryResult}>

View File

@ -8,16 +8,16 @@ import { useApi } from 'components/hooks';
function useValues(websiteId, type) {
const now = Date.now();
const { get, useQuery } = useApi();
const { data, error, isLoading } = useQuery(
['websites:values', websiteId, type],
() =>
const { data, error, isLoading } = useQuery({
queryKey: ['websites:values', websiteId, type],
queryFn: () =>
get(`/websites/${websiteId}/values`, {
type,
startAt: +subDays(now, 90),
endAt: now,
}),
{ enabled: !!(websiteId && type) },
);
enabled: !!(websiteId && type),
});
return { data, error, isLoading };
}

View File

@ -14,7 +14,10 @@ const reports = {
export default function ReportDetails({ reportId }) {
const { get, useQuery } = useApi();
const { data: report } = useQuery(['reports', reportId], () => get(`/reports/${reportId}`));
const { data: report } = useQuery({
queryKey: ['reports', reportId],
queryFn: () => get(`/reports/${reportId}`),
});
if (!report) {
return null;

View File

@ -12,16 +12,16 @@ import styles from './EventDataParameters.module.css';
function useFields(websiteId, startDate, endDate) {
const { get, useQuery } = useApi();
const { data, error, isLoading } = useQuery(
['fields', websiteId, startDate, endDate],
() =>
const { data, error, isLoading } = useQuery({
queryKey: ['fields', websiteId, startDate, endDate],
queryFn: () =>
get('/reports/event-data', {
websiteId,
startAt: +startDate,
endAt: +endDate,
}),
{ enabled: !!(websiteId && startDate && endDate) },
);
enabled: !!(websiteId && startDate && endDate),
});
return { data, error, isLoading };
}

View File

@ -8,10 +8,13 @@ import useCache from 'store/cache';
export function TeamsDataTable() {
const { get } = useApi();
const modified = useCache(state => state?.teams);
const queryResult = useFilterQuery(['teams', { modified }], params => {
return get(`/teams`, {
...params,
});
const queryResult = useFilterQuery({
queryKey: ['teams', { modified }],
queryFn: params => {
return get(`/teams`, {
...params,
});
},
});
return (

View File

@ -7,15 +7,15 @@ import useCache from 'store/cache';
export function TeamMembers({ teamId, readOnly }) {
const { get } = useApi();
const modified = useCache(state => state?.['team:members']);
const queryResult = useFilterQuery(
['team:members', { teamId, modified }],
params => {
const queryResult = useFilterQuery({
queryKey: ['team:members', { teamId, modified }],
queryFn: params => {
return get(`/teams/${teamId}/users`, {
...params,
});
},
{ enabled: !!teamId },
);
enabled: !!teamId,
});
return (
<>

View File

@ -17,15 +17,15 @@ export function TeamSettings({ teamId }) {
const [tab, setTab] = useState('details');
const { get, useQuery } = useApi();
const { showToast } = useToasts();
const { data, isLoading } = useQuery(
['team', teamId],
() => {
const { data, isLoading } = useQuery({
queryKey: ['team', teamId],
queryFn: () => {
if (teamId) {
return get(`/teams/${teamId}`);
}
},
{ cacheTime: 0 },
);
cacheTime: 0,
});
const canEdit = data?.teamUser?.find(
({ userId, role }) => role === ROLES.teamOwner && userId === user.id,
);

View File

@ -12,7 +12,10 @@ export function TeamWebsiteAddForm({ teamId, onSave, onClose }) {
const { formatMessage, labels } = useMessages();
const { get, post, useQuery, useMutation } = useApi();
const { mutate, error } = useMutation(data => post(`/teams/${teamId}/websites`, data));
const { data: websites, isLoading } = useQuery(['websites'], () => get('/websites'));
const { data: websites, isLoading } = useQuery({
queryKey: ['websites'],
queryFn: () => get('/websites'),
});
const [selected, setSelected] = useState([]);
const hasData = websites && websites.data.length > 0;

View File

@ -13,15 +13,15 @@ export function TeamWebsites({ teamId }) {
const { user } = useUser();
const { get } = useApi();
const modified = useCache(state => state?.['team:websites']);
const queryResult = useFilterQuery(
['team:websites', { teamId, modified }],
params => {
const queryResult = useFilterQuery({
queryKey: ['team:websites', { teamId, modified }],
queryFn: params => {
return get(`/teams/${teamId}/websites`, {
...params,
});
},
{ enabled: !!user },
);
enabled: !!user,
});
const handleChange = () => {
queryResult.refetch();

View File

@ -7,15 +7,15 @@ export function UserWebsites({ userId }) {
const { filter, page, pageSize, handleFilterChange, handlePageChange, handlePageSizeChange } =
useApiFilter();
const { get, useQuery } = useApi();
const { data, isLoading, error } = useQuery(
['user:websites', userId, filter, page, pageSize],
() =>
const { data, isLoading, error } = useQuery({
queryKey: ['user:websites', userId, filter, page, pageSize],
queryFn: () =>
get(`/users/${userId}/websites`, {
filter,
page,
pageSize,
}),
);
});
const hasData = data && data.length !== 0;
return (

View File

@ -9,10 +9,9 @@ import useCache from 'store/cache';
export function UsersDataTable() {
const { get } = useApi();
const modified = useCache(state => state?.users);
const queryResult = useFilterQuery(['users', { modified }], params => {
return get(`/users`, {
...params,
});
const queryResult = useFilterQuery({
queryKey: ['users', { modified }],
queryFn: params => get(`/users`, params),
});
return (

View File

@ -14,15 +14,15 @@ export function UserSettings({ userId }) {
const [tab, setTab] = useState('details');
const { get, useQuery } = useApi();
const { showToast } = useToasts();
const { data, isLoading } = useQuery(
['user', userId],
() => {
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => {
if (userId) {
return get(`/users/${userId}`);
}
},
{ cacheTime: 0 },
);
cacheTime: 0,
});
const handleSave = data => {
showToast({ message: formatMessage(messages.saved), variant: 'success' });

View File

@ -1,6 +1,6 @@
'use client';
import { useEffect, useState } from 'react';
import { Item, Tabs, useToasts, Button, Text, Icon, Icons } from 'react-basics';
import { Item, Tabs, useToasts, Button, Text, Icon, Icons, Loading } from 'react-basics';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import PageHeader from 'components/layout/PageHeader';
@ -16,7 +16,9 @@ export function WebsiteSettings({ websiteId, openExternal = false, analyticsUrl
const { formatMessage, labels, messages } = useMessages();
const { get, useQuery } = useApi();
const { showToast } = useToasts();
const { data } = useQuery(['website', websiteId], () => get(`/websites/${websiteId}`), {
const { data, isLoading } = useQuery({
queryKey: ['website', websiteId],
queryFn: () => get(`/websites/${websiteId}`),
enabled: !!websiteId,
cacheTime: 0,
});
@ -46,6 +48,10 @@ export function WebsiteSettings({ websiteId, openExternal = false, analyticsUrl
}
}, [data]);
if (isLoading || !values) {
return <Loading />;
}
return (
<>
<PageHeader title={values?.name}>

View File

@ -21,17 +21,17 @@ function useWebsites(userId: string, { includeTeams, onlyTeams }) {
const { get } = useApi();
const modified = useCache((state: any) => state?.websites);
return useFilterQuery(
['websites', { includeTeams, onlyTeams, modified }],
(params: any) => {
return useFilterQuery({
queryKey: ['websites', { includeTeams, onlyTeams, modified }],
queryFn: (params: any) => {
return get(`/users/${userId}/websites`, {
includeTeams,
onlyTeams,
...params,
});
},
{ enabled: !!userId },
);
enabled: !!userId,
});
}
export function WebsitesDataTable({

View File

@ -12,12 +12,12 @@ export function WebsiteChart({ websiteId }) {
} = useNavigation();
const { get, useQuery } = useApi();
const { data, isLoading } = useQuery(
[
const { data, isLoading } = useQuery({
queryKey: [
'websites:pageviews',
{ websiteId, modified, url, referrer, os, browser, device, country, region, city, title },
],
() =>
queryFn: () =>
get(`/websites/${websiteId}/pageviews`, {
startAt: +startDate,
endAt: +endDate,
@ -33,7 +33,7 @@ export function WebsiteChart({ websiteId }) {
city,
title,
}),
);
});
const chartData = useMemo(() => {
if (data) {

View File

@ -17,12 +17,12 @@ export function WebsiteMetricsBar({ websiteId, showFilter = true, sticky }) {
query: { url, referrer, title, os, browser, device, country, region, city },
} = useNavigation();
const { data, error, isLoading, isFetched } = useQuery(
[
const { data, error, isLoading, isFetched } = useQuery({
queryKey: [
'websites:stats',
{ websiteId, modified, url, referrer, title, os, browser, device, country, region, city },
],
() =>
queryFn: () =>
get(`/websites/${websiteId}/stats`, {
startAt: +startDate,
endAt: +endDate,
@ -36,7 +36,7 @@ export function WebsiteMetricsBar({ websiteId, showFilter = true, sticky }) {
region,
city,
}),
);
});
const { pageviews, uniques, bounces, totaltime } = data || {};
const num = Math.min(data && uniques.value, data && bounces.value);

View File

@ -11,15 +11,15 @@ export function EventDataMetricsBar({ websiteId }) {
const [dateRange] = useDateRange(websiteId);
const { startDate, endDate, modified } = dateRange;
const { data, error, isLoading, isFetched } = useQuery(
['event-data:stats', { websiteId, startDate, endDate, modified }],
() =>
const { data, error, isLoading, isFetched } = useQuery({
queryKey: ['event-data:stats', { websiteId, startDate, endDate, modified }],
queryFn: () =>
get(`/event-data/stats`, {
websiteId,
startAt: +startDate,
endAt: +endDate,
}),
);
});
return (
<div className={styles.container}>

View File

@ -10,17 +10,17 @@ function useData(websiteId, event) {
const [dateRange] = useDateRange(websiteId);
const { startDate, endDate } = dateRange;
const { get, useQuery } = useApi();
const { data, error, isLoading } = useQuery(
['event-data:events', { websiteId, startDate, endDate, event }],
() =>
const { data, error, isLoading } = useQuery({
queryKey: ['event-data:events', { websiteId, startDate, endDate, event }],
queryFn: () =>
get('/event-data/events', {
websiteId,
startAt: +startDate,
endAt: +endDate,
event,
}),
{ enabled: !!(websiteId && startDate && endDate) },
);
enabled: !!(websiteId && startDate && endDate),
});
return { data, error, isLoading };
}

View File

@ -28,15 +28,13 @@ export function Realtime({ websiteId }) {
const [currentData, setCurrentData] = useState();
const { get, useQuery } = useApi();
const { data: website } = useWebsite(websiteId);
const { data, isLoading, error } = useQuery(
['realtime', websiteId],
() => get(`/realtime/${websiteId}`, { startAt: currentData?.timestamp || 0 }),
{
enabled: !!(websiteId && website),
refetchInterval: REALTIME_INTERVAL,
cache: false,
},
);
const { data, isLoading, error } = useQuery({
queryKey: ['realtime', websiteId],
queryFn: () => get(`/realtime/${websiteId}`, { startAt: currentData?.timestamp || 0 }),
enabled: !!(websiteId && website),
refetchInterval: REALTIME_INTERVAL,
cache: false,
});
useEffect(() => {
if (data) {

View File

@ -10,7 +10,10 @@ export function RealtimeHome() {
const { formatMessage, labels, messages } = useMessages();
const { get, useQuery } = useApi();
const router = useRouter();
const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));
const { data, isLoading, error } = useQuery({
queryKey: ['websites:me'],
queryFn: () => get('/me/websites'),
});
useEffect(() => {
if (data?.length) {

View File

@ -1,29 +1,16 @@
import { ReactNode, Dispatch, SetStateAction } from 'react';
import { ReactNode } from 'react';
import classNames from 'classnames';
import { Banner, Loading, SearchField } from 'react-basics';
import { useMessages } from 'components/hooks';
import Empty from 'components/common/Empty';
import Pager from 'components/common/Pager';
import styles from './DataTable.module.css';
import { FilterQueryResult } from 'components/hooks/useFilterQuery';
const DEFAULT_SEARCH_DELAY = 600;
export interface DataTableProps {
queryResult: {
result: {
page: number;
pageSize: number;
count: number;
data: any[];
};
params: {
query: string;
page: number;
};
setParams: Dispatch<SetStateAction<{ query: string; page: number }>>;
isLoading: boolean;
error: unknown;
};
queryResult: FilterQueryResult<any>;
searchDelay?: number;
allowSearch?: boolean;
allowPaging?: boolean;
@ -38,7 +25,12 @@ export function DataTable({
children,
}: DataTableProps) {
const { formatMessage, labels, messages } = useMessages();
const { result, error, isLoading, params, setParams } = queryResult || {};
const {
result,
params,
setParams,
query: { error, isLoading },
} = queryResult || {};
const { page, pageSize, count, data } = result || {};
const { query } = params || {};
const hasData = Boolean(!isLoading && data?.length);

View File

@ -13,7 +13,7 @@ export interface FilterLinkProps {
label?: string;
externalUrl?: string;
className?: string;
children: ReactNode;
children?: ReactNode;
}
export function FilterLink({

View File

@ -1,24 +1,25 @@
import { useState } from 'react';
import { useState, Dispatch, SetStateAction } from 'react';
import { useApi } from 'components/hooks/useApi';
import { UseQueryOptions } from '@tanstack/react-query';
import { SearchFilter, FilterResult } from 'lib/types';
export function useFilterQuery(key: any[], fn, options?: UseQueryOptions) {
const [params, setParams] = useState({
export interface FilterQueryResult<T> {
result: FilterResult<any[]>;
query: any;
params: SearchFilter;
setParams: Dispatch<SetStateAction<T | SearchFilter>>;
}
export function useFilterQuery<T>(props = {}): FilterQueryResult<T> {
const [params, setParams] = useState<T | SearchFilter>({
query: '',
page: 1,
});
const { useQuery } = useApi();
const { data, ...other } = useQuery([...key, params], fn.bind(null, params), options);
const { data, ...query } = useQuery<FilterResult<any[]>>({ ...props });
return {
result: data as {
page: number;
pageSize: number;
count: number;
data: any[];
},
...other,
result: data,
query,
params,
setParams,
};

View File

@ -8,10 +8,10 @@ export function useReports() {
const { mutate } = useMutation(reportId => del(`/reports/${reportId}`));
const { filter, page, pageSize, handleFilterChange, handlePageChange, handlePageSizeChange } =
useApiFilter();
const { data, error, isLoading } = useQuery(
['reports', { modified, filter, page, pageSize }],
() => get(`/reports`, { filter, page, pageSize }),
);
const { data, error, isLoading } = useQuery({
queryKey: ['reports', { modified, filter, page, pageSize }],
queryFn: () => get(`/reports`, { filter, page, pageSize }),
});
const deleteReport = id => {
mutate(id, {

View File

@ -6,12 +6,15 @@ const selector = (state: { shareToken: string }) => state.shareToken;
export function useShareToken(shareId: string) {
const shareToken = useStore(selector);
const { get, useQuery } = useApi();
const { isLoading, error } = useQuery(['share', shareId], async () => {
const data = await get(`/share/${shareId}`);
const { isLoading, error } = useQuery({
queryKey: ['share', shareId],
queryFn: async () => {
const data = await get(`/share/${shareId}`);
setShareToken(data);
setShareToken(data);
return data;
return data;
},
});
return { shareToken, isLoading, error };

View File

@ -2,7 +2,9 @@ import useApi from './useApi';
export function useWebsite(websiteId: string) {
const { get, useQuery } = useApi();
return useQuery(['websites', websiteId], () => get(`/websites/${websiteId}`), {
return useQuery({
queryKey: ['websites', websiteId],
queryFn: () => get(`/websites/${websiteId}`),
enabled: !!websiteId,
});
}

View File

@ -6,7 +6,10 @@ import styles from './WebsiteSelect.module.css';
export function WebsiteSelect({ websiteId, onSelect }) {
const { formatMessage, labels } = useMessages();
const { get, useQuery } = useApi();
const { data } = useQuery(['websites:me'], () => get('/me/websites', { pageSize: 100 }));
const { data } = useQuery({
queryKey: ['websites:me'],
queryFn: () => get('/me/websites', { pageSize: 100 }),
});
const renderValue = value => {
return data?.data?.find(({ id }) => id === value)?.name;

View File

@ -7,14 +7,12 @@ import styles from './ActiveUsers.module.css';
export function ActiveUsers({ websiteId, value, refetchInterval = 60000 }) {
const { formatMessage, messages } = useMessages();
const { get, useQuery } = useApi();
const { data } = useQuery(
['websites:active', websiteId],
() => get(`/websites/${websiteId}/active`),
{
refetchInterval,
enabled: !!websiteId,
},
);
const { data } = useQuery({
queryKey: ['websites:active', websiteId],
queryFn: () => get(`/websites/${websiteId}/active`),
refetchInterval,
enabled: !!websiteId,
});
const count = useMemo(() => {
if (websiteId) {

View File

@ -16,17 +16,20 @@ export function EventsChart({ websiteId, className, token }) {
query: { url, event },
} = useNavigation();
const { data, isLoading } = useQuery(['events', websiteId, modified, event], () =>
get(`/websites/${websiteId}/events`, {
startAt: +startDate,
endAt: +endDate,
unit,
timezone,
url,
event,
token,
}),
);
const { data, isLoading } = useQuery({
queryKey: ['events', websiteId, modified, event],
queryFn: () =>
get(`/websites/${websiteId}/events`, {
startAt: +startDate,
endAt: +endDate,
unit,
timezone,
url,
event,
token,
}),
enabled: !!websiteId,
});
const datasets = useMemo(() => {
if (!data) return [];

View File

@ -35,8 +35,8 @@ export function MetricsTable({
const { get, useQuery } = useApi();
const { dir } = useLocale();
const { data, isLoading, isFetched, error } = useQuery(
[
const { data, isLoading, isFetched, error } = useQuery({
queryKey: [
'websites:metrics',
{
websiteId,
@ -53,11 +53,13 @@ export function MetricsTable({
city,
},
],
() => {
queryFn: () => {
const filters = { url, title, referrer, os, browser, device, country, region, city };
filters[type] = undefined;
onDataLoad?.();
return get(`/websites/${websiteId}/metrics`, {
type,
startAt: +startDate,
@ -65,8 +67,8 @@ export function MetricsTable({
...filters,
});
},
{ onSuccess: onDataLoad, retryDelay: delay || DEFAULT_ANIMATION_DURATION },
);
retryDelay: delay || DEFAULT_ANIMATION_DURATION,
});
const filteredData = useMemo(() => {
if (data) {