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 }) { export function TestConsole({ websiteId }) {
const { get, useQuery } = useApi(); 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(); const { router } = useNavigation();
function handleChange(value) { function handleChange(value) {

View File

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

View File

@ -17,7 +17,10 @@ export function DashboardEdit() {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels } = useMessages();
const [order, setOrder] = useState(websiteOrder || []); const [order, setOrder] = useState(websiteOrder || []);
const { get, useQuery } = useApi(); 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 { data: websites } = result || {};
const ordered = useMemo(() => { const ordered = useMemo(() => {

View File

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

View File

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

View File

@ -14,7 +14,10 @@ const reports = {
export default function ReportDetails({ reportId }) { export default function ReportDetails({ reportId }) {
const { get, useQuery } = useApi(); 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) { if (!report) {
return null; return null;

View File

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

View File

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

View File

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

View File

@ -17,15 +17,15 @@ export function TeamSettings({ teamId }) {
const [tab, setTab] = useState('details'); const [tab, setTab] = useState('details');
const { get, useQuery } = useApi(); const { get, useQuery } = useApi();
const { showToast } = useToasts(); const { showToast } = useToasts();
const { data, isLoading } = useQuery( const { data, isLoading } = useQuery({
['team', teamId], queryKey: ['team', teamId],
() => { queryFn: () => {
if (teamId) { if (teamId) {
return get(`/teams/${teamId}`); return get(`/teams/${teamId}`);
} }
}, },
{ cacheTime: 0 }, cacheTime: 0,
); });
const canEdit = data?.teamUser?.find( const canEdit = data?.teamUser?.find(
({ userId, role }) => role === ROLES.teamOwner && userId === user.id, ({ 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 { formatMessage, labels } = useMessages();
const { get, post, useQuery, useMutation } = useApi(); const { get, post, useQuery, useMutation } = useApi();
const { mutate, error } = useMutation(data => post(`/teams/${teamId}/websites`, data)); 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 [selected, setSelected] = useState([]);
const hasData = websites && websites.data.length > 0; const hasData = websites && websites.data.length > 0;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,12 +12,12 @@ export function WebsiteChart({ websiteId }) {
} = useNavigation(); } = useNavigation();
const { get, useQuery } = useApi(); const { get, useQuery } = useApi();
const { data, isLoading } = useQuery( const { data, isLoading } = useQuery({
[ queryKey: [
'websites:pageviews', 'websites:pageviews',
{ websiteId, modified, url, referrer, os, browser, device, country, region, city, title }, { websiteId, modified, url, referrer, os, browser, device, country, region, city, title },
], ],
() => queryFn: () =>
get(`/websites/${websiteId}/pageviews`, { get(`/websites/${websiteId}/pageviews`, {
startAt: +startDate, startAt: +startDate,
endAt: +endDate, endAt: +endDate,
@ -33,7 +33,7 @@ export function WebsiteChart({ websiteId }) {
city, city,
title, title,
}), }),
); });
const chartData = useMemo(() => { const chartData = useMemo(() => {
if (data) { 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 }, query: { url, referrer, title, os, browser, device, country, region, city },
} = useNavigation(); } = useNavigation();
const { data, error, isLoading, isFetched } = useQuery( const { data, error, isLoading, isFetched } = useQuery({
[ queryKey: [
'websites:stats', 'websites:stats',
{ websiteId, modified, url, referrer, title, os, browser, device, country, region, city }, { websiteId, modified, url, referrer, title, os, browser, device, country, region, city },
], ],
() => queryFn: () =>
get(`/websites/${websiteId}/stats`, { get(`/websites/${websiteId}/stats`, {
startAt: +startDate, startAt: +startDate,
endAt: +endDate, endAt: +endDate,
@ -36,7 +36,7 @@ export function WebsiteMetricsBar({ websiteId, showFilter = true, sticky }) {
region, region,
city, city,
}), }),
); });
const { pageviews, uniques, bounces, totaltime } = data || {}; const { pageviews, uniques, bounces, totaltime } = data || {};
const num = Math.min(data && uniques.value, data && bounces.value); 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 [dateRange] = useDateRange(websiteId);
const { startDate, endDate, modified } = dateRange; const { startDate, endDate, modified } = dateRange;
const { data, error, isLoading, isFetched } = useQuery( const { data, error, isLoading, isFetched } = useQuery({
['event-data:stats', { websiteId, startDate, endDate, modified }], queryKey: ['event-data:stats', { websiteId, startDate, endDate, modified }],
() => queryFn: () =>
get(`/event-data/stats`, { get(`/event-data/stats`, {
websiteId, websiteId,
startAt: +startDate, startAt: +startDate,
endAt: +endDate, endAt: +endDate,
}), }),
); });
return ( return (
<div className={styles.container}> <div className={styles.container}>

View File

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

View File

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

View File

@ -10,7 +10,10 @@ export function RealtimeHome() {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages } = useMessages();
const { get, useQuery } = useApi(); const { get, useQuery } = useApi();
const router = useRouter(); 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(() => { useEffect(() => {
if (data?.length) { if (data?.length) {

View File

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

View File

@ -13,7 +13,7 @@ export interface FilterLinkProps {
label?: string; label?: string;
externalUrl?: string; externalUrl?: string;
className?: string; className?: string;
children: ReactNode; children?: ReactNode;
} }
export function FilterLink({ 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 { 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) { export interface FilterQueryResult<T> {
const [params, setParams] = useState({ 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: '', query: '',
page: 1, page: 1,
}); });
const { useQuery } = useApi(); const { useQuery } = useApi();
const { data, ...query } = useQuery<FilterResult<any[]>>({ ...props });
const { data, ...other } = useQuery([...key, params], fn.bind(null, params), options);
return { return {
result: data as { result: data,
page: number; query,
pageSize: number;
count: number;
data: any[];
},
...other,
params, params,
setParams, setParams,
}; };

View File

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

View File

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

View File

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

View File

@ -6,7 +6,10 @@ import styles from './WebsiteSelect.module.css';
export function WebsiteSelect({ websiteId, onSelect }) { export function WebsiteSelect({ websiteId, onSelect }) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels } = useMessages();
const { get, useQuery } = useApi(); 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 => { const renderValue = value => {
return data?.data?.find(({ id }) => id === value)?.name; 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 }) { export function ActiveUsers({ websiteId, value, refetchInterval = 60000 }) {
const { formatMessage, messages } = useMessages(); const { formatMessage, messages } = useMessages();
const { get, useQuery } = useApi(); const { get, useQuery } = useApi();
const { data } = useQuery( const { data } = useQuery({
['websites:active', websiteId], queryKey: ['websites:active', websiteId],
() => get(`/websites/${websiteId}/active`), queryFn: () => get(`/websites/${websiteId}/active`),
{ refetchInterval,
refetchInterval, enabled: !!websiteId,
enabled: !!websiteId, });
},
);
const count = useMemo(() => { const count = useMemo(() => {
if (websiteId) { if (websiteId) {

View File

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

View File

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