Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

move useLogsPreview to react-query

Alaister Young959a3e25ce9d
diff --git a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
index 825c7999281..543c32821d8 100644
--- a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
+++ b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
@@ -58,7 +58,7 @@ export const LogsPreviewer: React.FC<Props> = ({
const table = !tableName ? LOGS_TABLES[queryType] : tableName
const [
- { error, logData, params, newCount, filters, isLoading, eventChartData },
+ { error, logData, params, newCount, filters, isLoading, eventChartData, isLoadingOlder },
{ loadOlder, setFilters, refresh, setParams },
] = useLogsPreview(projectRef as string, table, filterOverride)
@@ -221,7 +221,13 @@ export const LogsPreviewer: React.FC<Props> = ({
</LoadingOpacity>
{!error && (
<div className="flex flex-row justify-between p-2">
- <Button onClick={loadOlder} icon={<IconRewind />} type="default">
+ <Button
+ onClick={loadOlder}
+ icon={<IconRewind />}
+ type="default"
+ loading={isLoadingOlder}
+ disabled={isLoadingOlder}
+ >
Load older
</Button>
<div className="flex flex-row justify-end mt-2">
diff --git a/studio/hooks/analytics/useLogsPreview.tsx b/studio/hooks/analytics/useLogsPreview.tsx
index fc65f7288de..422d15b04a2 100644
--- a/studio/hooks/analytics/useLogsPreview.tsx
+++ b/studio/hooks/analytics/useLogsPreview.tsx
@@ -1,3 +1,4 @@
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import {
Count,
EventChart,
@@ -15,8 +16,6 @@ import {
PREVIEWER_DATEPICKER_HELPERS,
} from 'components/interfaces/Settings/Logs'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
-import useSWR from 'swr'
-import useSWRInfinite, { SWRInfiniteKeyLoader } from 'swr/infinite'
import { API_URL } from 'lib/constants'
import { get } from 'lib/common/fetch'
import dayjs from 'dayjs'
@@ -26,7 +25,7 @@ interface Data {
error: string | Object | null
newCount: number
isLoading: boolean
- pageSize: number
+ isLoadingOlder: boolean
filters: Filters
params: LogsEndpointParams
oldestTimestamp?: string
@@ -64,51 +63,42 @@ function useLogsPreview(
refresh()
}, [JSON.stringify(filters)])
- // handle url generation for log pagination
- const getKeyLogs: SWRInfiniteKeyLoader = (_pageIndex: number, prevPageData: Logs) => {
- let queryParams
-
- // cancel request if no sql provided
- if (!params.sql) {
- // return null to restrict unnecessary requests to api
- // https://swr.vercel.app/docs/conditional-fetching#conditional
- return null
- }
-
- // if prev page data is 100 items, could possibly have more records that are not yet fetched within this interval
- if (prevPageData === null) {
- // reduce interval window limit by using the timestamp of the last log
- queryParams = genQueryParams(params as any)
- } else if ((prevPageData.result ?? []).length === 0) {
- // no rows returned, indicates that no more data to retrieve and append.
- return null
- } else {
- const len = prevPageData.result.length
- const { timestamp: tsLimit }: LogData = prevPageData.result[len - 1]
- const isoTsLimit = dayjs.utc(Number(tsLimit / 1000)).toISOString()
- // create new key from params
- queryParams = genQueryParams({ ...params, iso_timestamp_end: isoTsLimit } as any)
+ const {
+ data,
+ isLoading,
+ isRefetching,
+ error: rqError,
+ fetchNextPage,
+ isFetchingNextPage,
+ refetch,
+ } = useInfiniteQuery(
+ ['projects', projectRef, 'logs', params],
+ ({ signal, pageParam }) => {
+ return get<Logs>(
+ `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams({
+ ...params,
+ iso_timestamp_end: pageParam,
+ } as any)}`,
+ { signal }
+ )
+ },
+ {
+ refetchOnWindowFocus: false,
+ getNextPageParam(lastPage) {
+ if (lastPage.result.length === 0) {
+ return undefined
+ }
+ const len = lastPage.result.length
+ const { timestamp: tsLimit }: LogData = lastPage.result[len - 1]
+ const isoTsLimit = dayjs.utc(Number(tsLimit / 1000)).toISOString()
+ return isoTsLimit
+ },
}
- return `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${queryParams}`
- }
+ )
- const {
- data = [],
- error: swrError,
- isValidating,
- size,
- setSize,
- } = useSWRInfinite<Logs>(getKeyLogs, get, { revalidateOnFocus: false, dedupingInterval: 3000 })
let logData: LogData[] = []
const countUrl = () => {
- // cancel request if no sql provided
- if (!params.sql) {
- // return null to restrict unnecessary requests to api
- // https://swr.vercel.app/docs/conditional-fetching#conditional
- return null
- }
-
return `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams({
...params,
sql: genCountQuery(table, filters),
@@ -116,24 +106,26 @@ function useLogsPreview(
} as any)}`
}
- const { data: countData } = useSWR<Count>(countUrl, get, {
- revalidateOnFocus: false,
- dedupingInterval: 5000,
- refreshInterval: 5000,
- })
+ const { data: countData } = useQuery(
+ [
+ 'projects',
+ projectRef,
+ 'logs-count',
+ { ...params, sql: genCountQuery(table, filters), iso_timestamp_start: latestRefresh },
+ ],
+ ({ signal }) => get<Count>(countUrl(), { signal }),
+ {
+ refetchOnWindowFocus: false,
+ refetchInterval: 5000,
+ }
+ )
+
const newCount = countData?.result?.[0]?.count ?? 0
// chart data
const chartQuery = genChartQuery(table, params, filters)
const chartUrl = () => {
- // cancel request if no sql provided
- if (!params.sql) {
- // return null to restrict unnecessary requests to api
- // https://swr.vercel.app/docs/conditional-fetching#conditional
- return null
- }
-
return `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams({
iso_timestamp_end: params.iso_timestamp_end,
project: params.project,
@@ -141,26 +133,27 @@ function useLogsPreview(
} as any)}`
}
- const { data: eventChartResponse, mutate: refreshEventChart } = useSWR<EventChart>(
- chartUrl,
- get,
- {
- revalidateOnFocus: false,
- dedupingInterval: 10000,
- refreshInterval: 0,
- }
+ const { data: eventChartResponse, refetch: refreshEventChart } = useQuery(
+ [
+ 'projects',
+ projectRef,
+ 'logs-chart',
+ { iso_timestamp_end: params.iso_timestamp_end, project: params.project, sql: chartQuery },
+ ],
+ ({ signal }) => get<EventChart>(chartUrl(), { signal }),
+ { refetchOnWindowFocus: false }
)
const refresh = async () => {
const generatedSql = genDefaultQuery(table, filters)
setParams((prev) => ({ ...prev, sql: generatedSql }))
setLatestRefresh(new Date().toISOString())
- setSize(1)
refreshEventChart()
+ refetch()
}
- let error: null | string | object = swrError ? swrError.message : null
- data.forEach((response) => {
+ let error: null | string | object = rqError ? (rqError as any).message : null
+ data?.pages.forEach((response) => {
if (!error && response?.result) {
logData = [...logData, ...response.result]
}
@@ -185,8 +178,8 @@ function useLogsPreview(
{
newCount,
logData,
- isLoading: isValidating,
- pageSize: size,
+ isLoading: isLoading || isRefetching,
+ isLoadingOlder: isFetchingNextPage,
error,
filters,
params,
@@ -196,7 +189,7 @@ function useLogsPreview(
{
setFilters: handleSetFilters,
refresh,
- loadOlder: () => setSize((prev) => prev + 1),
+ loadOlder: () => fetchNextPage(),
setParams,
},
]