From 4251a58aa55cf5009bd640eeb41422ba16717d80 Mon Sep 17 00:00:00 2001 From: "Federico Pasqua (eisterman)" Date: Wed, 2 Apr 2025 16:17:17 +0200 Subject: [PATCH] Experiment with React-Query --- eslint.config.mjs | 2 + package.json | 2 + pnpm-lock.yaml | 50 +++++++++++++++++++---- src/app/(sidebar)/layout.tsx | 27 +++++++++--- src/app/(sidebar)/loaders.ts | 28 +++++++++---- src/app/(sidebar)/sidebar-contacts.tsx | 19 ++++++--- src/app/api/contacts/[contactId]/route.ts | 11 +++++ src/app/api/contacts/route.ts | 8 ++++ src/app/layout.tsx | 3 +- src/app/providers.tsx | 49 ++++++++++++++++++++++ 10 files changed, 169 insertions(+), 30 deletions(-) create mode 100644 src/app/api/contacts/[contactId]/route.ts create mode 100644 src/app/api/contacts/route.ts create mode 100644 src/app/providers.tsx diff --git a/eslint.config.mjs b/eslint.config.mjs index c85fb67..16d6221 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,6 +1,7 @@ import { dirname } from "path"; import { fileURLToPath } from "url"; import { FlatCompat } from "@eslint/eslintrc"; +import pluginQuery from '@tanstack/eslint-plugin-query'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -11,6 +12,7 @@ const compat = new FlatCompat({ const eslintConfig = [ ...compat.extends("next/core-web-vitals", "next/typescript"), + ...pluginQuery.configs['flat/recommended'], ]; export default eslintConfig; diff --git a/package.json b/package.json index 944cdd3..670a691 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "lint": "next lint" }, "dependencies": { + "@tanstack/react-query": "^5.71.3", "lowdb": "^7.0.1", "match-sorter": "^8.0.0", "next": "15.2.4", @@ -21,6 +22,7 @@ "devDependencies": { "@eslint/eslintrc": "^3", "@next/eslint-plugin-next": "^15.2.4", + "@tanstack/eslint-plugin-query": "^5.68.0", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 90600af..7e957db 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + '@tanstack/react-query': + specifier: ^5.71.3 + version: 5.71.3(react@19.1.0) lowdb: specifier: ^7.0.1 version: 7.0.1 @@ -39,6 +42,9 @@ importers: '@next/eslint-plugin-next': specifier: ^15.2.4 version: 15.2.4 + '@tanstack/eslint-plugin-query': + specifier: ^5.68.0 + version: 5.68.0(eslint@9.23.0)(typescript@5.8.2) '@types/node': specifier: ^20 version: 20.17.29 @@ -324,6 +330,19 @@ packages: '@swc/helpers@0.5.15': resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} + '@tanstack/eslint-plugin-query@5.68.0': + resolution: {integrity: sha512-w/+y5LILV1GTWBB2R/lKfUzgocKXU1B7O6jipLUJhmxCKPmJFy5zpfR1Vx7c6yCEsQoKcTbhuR/tIy+1sIGaiA==} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + + '@tanstack/query-core@5.71.3': + resolution: {integrity: sha512-SW7PXYpKiQCZU5pPOXG2UiHX1oSAxLyxoJiYbQ3aLYiABJW0UnfBZ9PVnO/x4ZCIVK30wfDn0h6Mrsr10q922Q==} + + '@tanstack/react-query@5.71.3': + resolution: {integrity: sha512-4GZxKqiMX+CH4CxXiUBNipbqzk2V5jUU8Z4d6J+lSDu8OejcLtjx1hEDJzabFZHwd+ZHCsYLAJmM54kCS1/ekA==} + peerDependencies: + react: ^18 || ^19 + '@tybys/wasm-util@0.9.0': resolution: {integrity: sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==} @@ -1779,6 +1798,21 @@ snapshots: dependencies: tslib: 2.8.1 + '@tanstack/eslint-plugin-query@5.68.0(eslint@9.23.0)(typescript@5.8.2)': + dependencies: + '@typescript-eslint/utils': 8.29.0(eslint@9.23.0)(typescript@5.8.2) + eslint: 9.23.0 + transitivePeerDependencies: + - supports-color + - typescript + + '@tanstack/query-core@5.71.3': {} + + '@tanstack/react-query@5.71.3(react@19.1.0)': + dependencies: + '@tanstack/query-core': 5.71.3 + react: 19.1.0 + '@tybys/wasm-util@0.9.0': dependencies: tslib: 2.8.1 @@ -2264,8 +2298,8 @@ snapshots: '@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2) eslint: 9.23.0 eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.0(eslint-plugin-import@2.31.0)(eslint@9.23.0) - eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0)(eslint@9.23.0) + eslint-import-resolver-typescript: 3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0) + eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0))(eslint@9.23.0) eslint-plugin-jsx-a11y: 6.10.2(eslint@9.23.0) eslint-plugin-react: 7.37.4(eslint@9.23.0) eslint-plugin-react-hooks: 5.2.0(eslint@9.23.0) @@ -2284,7 +2318,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0)(eslint@9.23.0): + eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0): dependencies: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.0 @@ -2295,22 +2329,22 @@ snapshots: tinyglobby: 0.2.12 unrs-resolver: 1.3.3 optionalDependencies: - eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0)(eslint@9.23.0) + eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0))(eslint@9.23.0) transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.0)(eslint@9.23.0): + eslint-module-utils@2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0))(eslint@9.23.0): dependencies: debug: 3.2.7 optionalDependencies: '@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2) eslint: 9.23.0 eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.0(eslint-plugin-import@2.31.0)(eslint@9.23.0) + eslint-import-resolver-typescript: 3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0) transitivePeerDependencies: - supports-color - eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0)(eslint@9.23.0): + eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0))(eslint@9.23.0): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.8 @@ -2321,7 +2355,7 @@ snapshots: doctrine: 2.1.0 eslint: 9.23.0 eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.0)(eslint@9.23.0) + eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.23.0)(typescript@5.8.2))(eslint@9.23.0))(eslint@9.23.0))(eslint@9.23.0) hasown: 2.0.2 is-core-module: 2.16.1 is-glob: 4.0.3 diff --git a/src/app/(sidebar)/layout.tsx b/src/app/(sidebar)/layout.tsx index b2a7752..d6645fa 100644 --- a/src/app/(sidebar)/layout.tsx +++ b/src/app/(sidebar)/layout.tsx @@ -2,9 +2,14 @@ import React, { Suspense } from "react"; import Link from "next/link"; import Form from "next/form"; import ContactList from "./sidebar-contacts"; -import { createEmptyContact } from "@/app/data"; +import { createEmptyContact, getContacts } from "@/app/data"; import { revalidatePath } from "next/cache"; import { fetchContacts } from "@/app/(sidebar)/loaders"; +import { + QueryClient, + dehydrate, + HydrationBoundary, +} from "@tanstack/react-query"; async function newContact() { "use server"; @@ -12,12 +17,22 @@ async function newContact() { revalidatePath('/'); } -export default function SidebarRootLayout({ +export default async function SidebarRootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { - const contacts = fetchContacts(); + const queryClient = new QueryClient(); + await queryClient.prefetchQuery({ + queryKey: ['contacts'], + queryFn: () => getContacts(), + }); + /* + * The problem here was that the `fetch` that Next uses inside function called server-side is the Node one, where you + * cannot use Relative Paths!!! + * So the most simple solution was to bypass the fetch and directly call the data function here. + * Basically the API is used only for the data refresh. + */ return ( <> @@ -43,9 +58,9 @@ export default function SidebarRootLayout({
diff --git a/src/app/(sidebar)/loaders.ts b/src/app/(sidebar)/loaders.ts index 6df7e48..f9a1d42 100644 --- a/src/app/(sidebar)/loaders.ts +++ b/src/app/(sidebar)/loaders.ts @@ -1,11 +1,21 @@ -import { getContact, getContacts } from "@/app/data"; +import { ContactRecord } from "@/app/data"; -export const fetchContacts = async () => { - console.log("fetch contacts") - return await getContacts(); -}; +export async function fetchContacts() { + console.log("fetchContacts()"); + const response = await fetch('/api/contacts'); + if (!response.ok) { + console.log("ERROR!?"); + throw new Error(`Network Error ${response.status}: ${response.statusText}`); + } + const data: { contacts: ContactRecord[] } = await response.json(); + return data.contacts; +} -export const fetchContact = async (contactId: string) => { - console.log(`fetch contact ${contactId}`) - return await getContact(contactId); -}; +export async function fetchContact(contactId: string) { + console.log("fetchContacts()"); + const response = await fetch(`/api/contacts/${contactId}`); + if (!response.ok) { + throw new Error(`Network Error ${response.status}: ${response.statusText}`); + } + return (await response.json())['contact'] as ContactRecord; +} diff --git a/src/app/(sidebar)/sidebar-contacts.tsx b/src/app/(sidebar)/sidebar-contacts.tsx index eb0cebe..0c7a871 100644 --- a/src/app/(sidebar)/sidebar-contacts.tsx +++ b/src/app/(sidebar)/sidebar-contacts.tsx @@ -1,12 +1,19 @@ -import { ContactRecord } from "@/app/data"; -import React, { use } from "react"; -import Link from "next/link"; +"use client"; + +import Link from "next/link"; +import { useQuery } from "@tanstack/react-query"; +import { fetchContacts } from "@/app/(sidebar)/loaders"; + +export default function ContactList() { + const { data } = useQuery({ + queryKey: ['contacts'], + queryFn: () => fetchContacts() + }); + if (data === undefined) return
Error during prefetch...
; -export default function ContactList({ contacts }: { contacts: Promise }) { - const allContacts = use(contacts); return (
    - {allContacts.map((c) => ( + {data.map((c) => (
  • {c.first || c.last ? ( diff --git a/src/app/api/contacts/[contactId]/route.ts b/src/app/api/contacts/[contactId]/route.ts new file mode 100644 index 0000000..2d31f4a --- /dev/null +++ b/src/app/api/contacts/[contactId]/route.ts @@ -0,0 +1,11 @@ +import { NextResponse } from 'next/server'; +import { getContact } from "@/app/data"; + +export async function GET( + { params }: { params: Promise<{ contactId: string }> } +) { + const { contactId } = await params; + console.log(`fetch contact ${contactId}`); + const contact = await getContact(contactId); + return NextResponse.json({ contact: contact }); +} \ No newline at end of file diff --git a/src/app/api/contacts/route.ts b/src/app/api/contacts/route.ts new file mode 100644 index 0000000..b907feb --- /dev/null +++ b/src/app/api/contacts/route.ts @@ -0,0 +1,8 @@ +import { NextResponse } from 'next/server'; +import { getContacts } from "@/app/data"; + +export async function GET() { + console.log("fetch contacts"); + const contacts = await getContacts(); + return NextResponse.json({ contacts: contacts }); +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 7406ee3..67f6304 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -2,6 +2,7 @@ import React from "react"; import type { Metadata } from "next"; import "./globals.css"; +import Providers from "@/app/providers"; export const metadata: Metadata = { title: "Next.js Address Book", @@ -16,7 +17,7 @@ export default function RootLayout({ return ( - {children} + {children} ); diff --git a/src/app/providers.tsx b/src/app/providers.tsx new file mode 100644 index 0000000..4913781 --- /dev/null +++ b/src/app/providers.tsx @@ -0,0 +1,49 @@ +'use client'; + +// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top +import { + isServer, + QueryClient, + QueryClientProvider, +} from '@tanstack/react-query'; +import React from "react"; + +function makeQueryClient() { + return new QueryClient({ + defaultOptions: { + queries: { + // With SSR, we usually want to set some default staleTime + // above 0 to avoid refetching immediately on the client + staleTime: 60 * 1000, + }, + }, + }); +} + +let browserQueryClient: QueryClient | undefined = undefined; + +function getQueryClient() { + if (isServer) { + // Server: always make a new query client + return makeQueryClient(); + } else { + // Browser: make a new query client if we don't already have one + // This is very important, so we don't re-make a new client if React + // suspends during the initial render. This may not be needed if we + // have a suspense boundary BELOW the creation of the query client + if (!browserQueryClient) browserQueryClient = makeQueryClient(); + return browserQueryClient; + } +} + +export default function Providers({ children }: { children: React.ReactNode }) { + // NOTE: Avoid useState when initializing the query client if you don't + // have a suspense boundary between this and the code that may + // suspend because React will throw away the client on the initial + // render if it suspends and there is no boundary + const queryClient = getQueryClient(); + + return ( + {children} + ); +} \ No newline at end of file