···1010tag: engineering
1111---
12121313-This article is part of the [logs.run](https://logs.run) series. You can enable the live mode right away via [logs.run/i?live=true](https://logs.run/i?live=true).
1313+This article is part of the [logs.run](https://logs.run) series.
14141515-While TanStack provides excellent documentation on [Infinite Queries](https://tanstack.com/query/latest/docs/framework/react/guides/infinite-queries), this article offers an additional practical example focusing on implementing live data updates.
1515+You can enable the live mode right away via [logs.run/i?live=true](https://logs.run/i?live=true). Note that it's a demo; the data is mocked and not persisted. Live mode might take a while to load new data.
16161717-## Basic Concept
1717+While TanStack provides excellent documentation on [Infinite Queries](https://tanstack.com/query/latest/docs/framework/react/guides/infinite-queries), this article offers an additional practical example focusing on implementing a live data update.
18181919-Infinite queries work with "pages" of data. Each time you load new data, a new "page" is either appended or prepended to the `data.pages` array. To get a flat list of all data in the correct order, you simply use `flatMap`:
2020-2121-```ts
2222-const { data, fetchNextPage, fetchPreviousPage } =
2323- useInfiniteQuery(dataOptions);
2424-2525-const flatData = React.useMemo(
2626- () => data?.pages?.flatMap((page) => page.data ?? []) ?? [],
2727- [data?.pages],
2828-);
2929-```
1919+## Basic Concept
30203131-Once we understand the _load more_ (append data) functionality, we can mirror this approach to implement _live mode_ (prepend data).
2121+Infinite queries work with "pages" of data. Each time you load new data, a new "page" is either appended (_load more_ older data) or prepended (_live mode_ newer data) to the `data.pages` array defined by the `useInfiniteQuery` hook. In the documentation, you'll read `lastPage` and `firstPage` to refer to the last and first page respectively.
32223333-Each query requires two key parameters:
2323+Each query to our API endpoint requires two key parameters:
342435251. A `cursor` - a pointer indicating a position in the dataset
36262. A `direction` - specifying whether to fetch data before or after the cursor ("prev" or "next")
37273838-
2828+A timeline sketch of the infinite query behavior:
39294040-In our implementation, the `cursor` is a timestamp representing the last checked date:
3030+
41314242-```ts
4343-const dataOptions = {
4444- queryKey: "data-table",
4545- queryFn: async ({ pageParam }) => {
4646- const { cursor, direction } = pageParam;
4747- const res = await fetch(
4848- `/api/get/data?cursor=${cursor}&direction=${direction}`,
4949- );
5050- const json = await res.json();
5151- // For direction "next": { data: [...], nextCursor: 1741526294, prevCursor: null }
5252- // For direction "prev": { data: [...], nextCursor: null, prevCursor: 1741526295 }
5353- return json as ReturnType;
5454- },
5555- // Initialize with current timestamp for "load more" functionality
5656- initialPageParam: { cursor: new Date().getTime(), direction: "next" },
5757- getPreviousPageParam: (firstPage, allPages) => {
5858- if (!firstPage.prevCursor) return null;
5959- return { cursor: firstPage.prevCursor, direction: "prev" };
6060- },
6161- getNextPageParam: (lastPage, allPages) => {
6262- if (!lastPage.nextCursor) return null;
6363- return { cursor: lastPage.nextCursor, direction: "next" };
6464- },
6565-};
6666-```
6767-6868-The `getPreviousPageParam` and `getNextPageParam` functions receive the first and last pages respectively as their first parameter. This allows us to access the `prevCursor` and `nextCursor` values to track our position when loading more items or checking for updates in live mode.
6969-7070-TanStack provides helpful states like `isFetchingNextPage` and `isFetchingPreviousPage` for loading indicators, as well as `hasNextPage` and `hasPreviousPage` to check for available pages - especially useful for as we can hit the end of the load more values.
3232+## API Endpoint
71337234Your API endpoint should return at minimum:
73357436```ts
7537type ReturnType<T> = {
3838+ // The single "page" data to be rendered
7639 data: T[];
4040+ // The timestamp to be used for the next page on _load more_
7741 nextCursor?: number | null;
4242+ // The timestamp to be used for the previous page on _live mode_
7843 prevCursor?: number | null;
7944};
8045```
81468282-When fetching older pages ("next" direction), we set a `LIMIT` (e.g., 40 items). However, when fetching newer data ("prev" direction), we return all data between the `prevCursor` and `Date.now()`.
4747+When fetching older pages ("next" direction), we set a `LIMIT` clause (e.g., 40 items). However, when fetching newer data ("prev" direction), we return all data between the `prevCursor` and `Date.now()`.
83488484-Example API implementation:
4949+Let's take a look at an example implementation of the API endpoint:
85508651```ts
5252+// import ...
5353+5454+type TData = {
5555+ id: string;
5656+ timestamp: number;
5757+ // ...
5858+};
5959+8760export async function GET(req: NextRequest) {
8861 const searchParams = request.nextUrl.searchParams;
8962 const cursor = searchParams.get("cursor");
···9770 WHERE timestamp > ${cursor} AND timestamp <= ${prevCursor}
9871 ORDER BY timestamp DESC
9972 `;
100100- const res: ReturnType<MyData> = { data, prevCursor, nextCursor: null };
7373+ const res: ReturnType<TData> = { data, prevCursor, nextCursor: null };
10174 return Response.json(res);
10275 // Load more
10376 } else {
···10881 LIMIT 40
10982 `;
11083 const nextCursor = data.length > 0 ? data[data.length - 1].timestamp : null;
111111- const res: ReturnType<MyData> = { data, nextCursor, prevCursor: null };
8484+ const res: ReturnType<TData> = { data, nextCursor, prevCursor: null };
11285 return Response.json(res);
11386 }
11487}
···1168911790Key points:
11891119119-- Live mode ("prev" direction): Returns all new data between `Date.now()` and the `cursor`
120120-- Load more ("next" direction): Returns 40 items before the `cursor` and updates `nextCursor`
9292+- _Live mode_ ("prev" direction): Returns all new data between `Date.now()` and the `cursor` from the first page
9393+- _Load more_ ("next" direction): Returns 40 items before the `cursor` of the last page and updates `nextCursor`
12194122122-> Important: Be careful with timestamp boundaries. If items share the same timestamp, you might miss data because of the `>` comparison. To prevent data loss, include all items sharing the same timestamp as the last item in your query.
9595+> **Important**: Be careful with timestamp boundaries. If items share the same timestamp, you might miss data because of the `>` comparison. To prevent data loss, include all items sharing the same timestamp as the last item in your query.
12396124124-### Avoiding OFFSET with Frequent Data Updates
9797+### Avoid Using OFFSET with Frequent Data Updates in Non-Live Mode
12598126126-While it might be tempting to use `OFFSET` for pagination (without having live mode active), this approach can cause problems when data is frequently prepended:
9999+While it might be tempting to use the cursor as an `OFFSET` for pagination (e.g. `?cursor=1`, `?cursor=2`, ...), the following approach can cause problems when data is frequently prepended:
127100128101```ts
102102+const limit = 40;
103103+const offset = limit * cursor;
104104+129105const data = await sql`
130106 SELECT * FROM table
131107 ORDER BY timestamp DESC
···134110`;
135111```
136112113113+When new items are prepended, they shift the offset values, causing duplicate items in subsequent queries.
114114+137115
138116139139-When new items are prepended, they shift the offset values, potentially causing duplicate items in subsequent queries.
117117+## Client Implementation
140118141141-### Implementing Auto-Refresh
119119+Let's call our API endpoint from the client and use the dedicated infinite query functions that are added to the `useQuery` hook.
142120143143-While TanStack Query provides a `refetchInterval` option, it would refetch all pages, growing increasingly expensive as more pages are loaded. Instead, we implement a custom refresh mechanism for fetching only new data:
121121+```tsx
122122+"use client";
123123+124124+import React from "react";
125125+import { useInfiniteQuery } from "@tanstack/react-query";
126126+127127+const dataOptions = {
128128+ queryKey: [
129129+ "my-key",
130130+ // any other keys, e.g. for search params filters
131131+ ],
132132+ queryFn: async ({ pageParam }) => {
133133+ const { cursor, direction } = pageParam;
134134+ const res = await fetch(
135135+ `/api/get/data?cursor=${cursor}&direction=${direction}`,
136136+ );
137137+ const json = await res.json();
138138+ // For direction "next": { data: [...], nextCursor: 1741526294, prevCursor: null }
139139+ // For direction "prev": { data: [...], nextCursor: null, prevCursor: 1741526295 }
140140+ return json as ReturnType;
141141+ },
142142+ // Initialize with current timestamp and get the most recent data in the past
143143+ initialPageParam: { cursor: new Date().getTime(), direction: "next" },
144144+ // Function to fetch newer data
145145+ getPreviousPageParam: (firstPage, allPages) => {
146146+ if (!firstPage.prevCursor) return null;
147147+ return { cursor: firstPage.prevCursor, direction: "prev" };
148148+ },
149149+ // Function to fetch older data
150150+ getNextPageParam: (lastPage, allPages) => {
151151+ if (!lastPage.nextCursor) return null;
152152+ return { cursor: lastPage.nextCursor, direction: "next" };
153153+ },
154154+};
155155+156156+export function Component() {
157157+ const { data, fetchNextPage, fetchPreviousPage } = useInfiniteQuery(dataOptions);
158158+159159+ const flatData = React.useMemo(
160160+ () => data?.pages?.flatMap((page) => page.data ?? []) ?? [],
161161+ [data?.pages],
162162+ );
163163+164164+ return <div>{flatData.map((item) => {/* render item */})}</div>;
165165+}
166166+```
167167+168168+The `getPreviousPageParam` and `getNextPageParam` functions receive the first and last pages respectively as their first parameter. This allows us to access the return values from the API, `prevCursor` and `nextCursor` and to track our position of the `cursor` in the dataset.
169169+170170+TanStack provides helpful states like `isFetchingNextPage` and `isFetchingPreviousPage` for loading indicators, as well as `hasNextPage` and `hasPreviousPage` to check for available pages - especially useful for as we can hit the end of the load more values. Check out the [`useInfiniteQuery`](https://tanstack.com/query/latest/docs/framework/react/reference/useInfiniteQuery) docs for more details.
171171+172172+## Implementing Auto-Refresh
173173+174174+While TanStack Query provides a `refetchInterval` option, it would refetch all pages, growing increasingly expensive as more pages are loaded. Additionally, it doesn't reflect the purpose of live mode as instead of refreshing the data, we want to fetch new data.
175175+176176+Therefore, we implement a custom refresh mechanism for fetching only new data that you can add to any client component. Here's an simple example implementation of the `LiveModeButton`:
144177145178```tsx
179179+"use client";
180180+181181+import * as React from "react";
182182+import type { FetchPreviousPageOptions } from "@tanstack/react-query";
183183+146184const REFRESH_INTERVAL = 5_000; // 5 seconds
147185148148-React.useEffect(() => {
149149- let timeoutId: NodeJS.Timeout;
186186+interface LiveModeButtonProps {
187187+ fetchPreviousPage?: (
188188+ options?: FetchPreviousPageOptions | undefined,
189189+ ) => Promise<unknown>;
190190+}
191191+192192+export function LiveModeButton({ fetchPreviousPage }: LiveModeButtonProps) {
193193+ // or nuqs [isLive, setIsLive] = useQueryState("live", parseAsBoolean)
194194+ const [isLive, setIsLive] = React.useState(false);
150195151151- async function fetchData() {
152152- // isLive is a simple boolean from React.useState<boolean>()
153153- // or nuqs useQueryState("live", parseAsBoolean)
154154- if (isLive) {
155155- await fetchPreviousPage?.();
156156- timeoutId = setTimeout(fetchData, REFRESH_INTERVAL);
157157- } else {
158158- clearTimeout(timeoutId);
159159- }
160160- }
196196+ React.useEffect(() => {
197197+ let timeoutId: NodeJS.Timeout;
198198+199199+ async function fetchData() {
200200+ if (isLive) {
201201+ await fetchPreviousPage();
202202+ // schedule the next fetch after REFRESH_INTERVAL
203203+ // once the current fetch completes
204204+ timeoutId = setTimeout(fetchData, REFRESH_INTERVAL);
205205+ } else {
206206+ clearTimeout(timeoutId);
207207+ }
208208+ }
209209+ fetchData();
161210162162- fetchData();
211211+ return () => clearTimeout(timeoutId);
212212+ }, [isLive, fetchPreviousPage]);
163213164164- return () => {
165165- clearTimeout(timeoutId);
166166- };
167167-}, [isLive, fetchPreviousPage]);
214214+ return <button onClick={() => setIsLive(!isLive)}>
215215+ {isLive ? "Stop live mode" : "Start live mode"}
216216+ </button>
217217+}
168218```
169219170220We use `setTimeout` with recursion rather than `setInterval` to ensure each refresh only starts after the previous one completes. This prevents multiple simultaneous fetches when network latency exceeds the refresh interval and is a better UX.
171221172222---
173223174174-Now check it out on [logs.run/i?live=true](https://logs.run/i?live=true).
224224+Go check it out on [logs.run/i?live=true](https://logs.run/i?live=true).
175225176176-For more details about our data table implementation, check out [The React data-table I always wanted](https://www.openstatus.dev/blog/data-table-redesign).
226226+For more details about our data table implementation, check out [The React data-table I always wanted](https://www.openstatus.dev/blog/data-table-redesign) blog post.