Compare commits

..

2 Commits

Author SHA1 Message Date
4251a58aa5 Experiment with React-Query 2025-04-02 16:17:17 +02:00
94346dd242 New Data handler with lowdb 2025-04-02 12:06:12 +02:00
11 changed files with 494 additions and 263 deletions

View File

@@ -1,6 +1,7 @@
import { dirname } from "path"; import { dirname } from "path";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc"; import { FlatCompat } from "@eslint/eslintrc";
import pluginQuery from '@tanstack/eslint-plugin-query';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename); const __dirname = dirname(__filename);
@@ -11,6 +12,7 @@ const compat = new FlatCompat({
const eslintConfig = [ const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"), ...compat.extends("next/core-web-vitals", "next/typescript"),
...pluginQuery.configs['flat/recommended'],
]; ];
export default eslintConfig; export default eslintConfig;

View File

@@ -9,6 +9,8 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.71.3",
"lowdb": "^7.0.1",
"match-sorter": "^8.0.0", "match-sorter": "^8.0.0",
"next": "15.2.4", "next": "15.2.4",
"react": "^19.0.0", "react": "^19.0.0",
@@ -20,6 +22,7 @@
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3", "@eslint/eslintrc": "^3",
"@next/eslint-plugin-next": "^15.2.4", "@next/eslint-plugin-next": "^15.2.4",
"@tanstack/eslint-plugin-query": "^5.68.0",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",

67
pnpm-lock.yaml generated
View File

@@ -8,6 +8,12 @@ importers:
.: .:
dependencies: 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
match-sorter: match-sorter:
specifier: ^8.0.0 specifier: ^8.0.0
version: 8.0.0 version: 8.0.0
@@ -36,6 +42,9 @@ importers:
'@next/eslint-plugin-next': '@next/eslint-plugin-next':
specifier: ^15.2.4 specifier: ^15.2.4
version: 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': '@types/node':
specifier: ^20 specifier: ^20
version: 20.17.29 version: 20.17.29
@@ -321,6 +330,19 @@ packages:
'@swc/helpers@0.5.15': '@swc/helpers@0.5.15':
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} 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': '@tybys/wasm-util@0.9.0':
resolution: {integrity: sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==} resolution: {integrity: sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==}
@@ -1121,6 +1143,10 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true hasBin: true
lowdb@7.0.1:
resolution: {integrity: sha512-neJAj8GwF0e8EpycYIDFqEPcx9Qz4GUho20jWFR7YiFeXzF1YMLdxB36PypcTSPMA+4+LvgyMacYhlr18Zlymw==}
engines: {node: '>=18'}
match-sorter@8.0.0: match-sorter@8.0.0:
resolution: {integrity: sha512-bGJ6Zb+OhzXe+ptP5d80OLVx7AkqfRbtGEh30vNSfjNwllu+hHI+tcbMIT/fbkx/FKN1PmKuDb65+Oofg+XUxw==} resolution: {integrity: sha512-bGJ6Zb+OhzXe+ptP5d80OLVx7AkqfRbtGEh30vNSfjNwllu+hHI+tcbMIT/fbkx/FKN1PmKuDb65+Oofg+XUxw==}
@@ -1407,6 +1433,10 @@ packages:
stable-hash@0.0.5: stable-hash@0.0.5:
resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==} resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}
steno@4.0.2:
resolution: {integrity: sha512-yhPIQXjrlt1xv7dyPQg2P17URmXbuM5pdGkpiMB3RenprfiBlvK415Lctfe0eshk90oA7/tNq7WEiMK8RSP39A==}
engines: {node: '>=18'}
streamsearch@1.1.0: streamsearch@1.1.0:
resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==} resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}
engines: {node: '>=10.0.0'} engines: {node: '>=10.0.0'}
@@ -1768,6 +1798,21 @@ snapshots:
dependencies: dependencies:
tslib: 2.8.1 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': '@tybys/wasm-util@0.9.0':
dependencies: dependencies:
tslib: 2.8.1 tslib: 2.8.1
@@ -2253,8 +2298,8 @@ snapshots:
'@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2) '@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2)
eslint: 9.23.0 eslint: 9.23.0
eslint-import-resolver-node: 0.3.9 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)
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)
eslint-plugin-jsx-a11y: 6.10.2(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: 7.37.4(eslint@9.23.0)
eslint-plugin-react-hooks: 5.2.0(eslint@9.23.0) eslint-plugin-react-hooks: 5.2.0(eslint@9.23.0)
@@ -2273,7 +2318,7 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - 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: dependencies:
'@nolyfill/is-core-module': 1.0.39 '@nolyfill/is-core-module': 1.0.39
debug: 4.4.0 debug: 4.4.0
@@ -2284,22 +2329,22 @@ snapshots:
tinyglobby: 0.2.12 tinyglobby: 0.2.12
unrs-resolver: 1.3.3 unrs-resolver: 1.3.3
optionalDependencies: 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: transitivePeerDependencies:
- supports-color - 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: dependencies:
debug: 3.2.7 debug: 3.2.7
optionalDependencies: optionalDependencies:
'@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2) '@typescript-eslint/parser': 8.29.0(eslint@9.23.0)(typescript@5.8.2)
eslint: 9.23.0 eslint: 9.23.0
eslint-import-resolver-node: 0.3.9 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: transitivePeerDependencies:
- supports-color - 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: dependencies:
'@rtsao/scc': 1.1.0 '@rtsao/scc': 1.1.0
array-includes: 3.1.8 array-includes: 3.1.8
@@ -2310,7 +2355,7 @@ snapshots:
doctrine: 2.1.0 doctrine: 2.1.0
eslint: 9.23.0 eslint: 9.23.0
eslint-import-resolver-node: 0.3.9 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 hasown: 2.0.2
is-core-module: 2.16.1 is-core-module: 2.16.1
is-glob: 4.0.3 is-glob: 4.0.3
@@ -2764,6 +2809,10 @@ snapshots:
dependencies: dependencies:
js-tokens: 4.0.0 js-tokens: 4.0.0
lowdb@7.0.1:
dependencies:
steno: 4.0.2
match-sorter@8.0.0: match-sorter@8.0.0:
dependencies: dependencies:
'@babel/runtime': 7.27.0 '@babel/runtime': 7.27.0
@@ -3100,6 +3149,8 @@ snapshots:
stable-hash@0.0.5: {} stable-hash@0.0.5: {}
steno@4.0.2: {}
streamsearch@1.1.0: {} streamsearch@1.1.0: {}
string.prototype.includes@2.0.1: string.prototype.includes@2.0.1:

View File

@@ -2,9 +2,14 @@ import React, { Suspense } from "react";
import Link from "next/link"; import Link from "next/link";
import Form from "next/form"; import Form from "next/form";
import ContactList from "./sidebar-contacts"; import ContactList from "./sidebar-contacts";
import { createEmptyContact } from "@/app/data"; import { createEmptyContact, getContacts } from "@/app/data";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { fetchContacts } from "@/app/(sidebar)/loaders"; import { fetchContacts } from "@/app/(sidebar)/loaders";
import {
QueryClient,
dehydrate,
HydrationBoundary,
} from "@tanstack/react-query";
async function newContact() { async function newContact() {
"use server"; "use server";
@@ -12,12 +17,22 @@ async function newContact() {
revalidatePath('/'); revalidatePath('/');
} }
export default function SidebarRootLayout({ export default async function SidebarRootLayout({
children, children,
}: Readonly<{ }: Readonly<{
children: React.ReactNode; 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 ( return (
<> <>
@@ -43,9 +58,9 @@ export default function SidebarRootLayout({
</Form> </Form>
</div> </div>
<nav> <nav>
<Suspense fallback={<div>Loading...</div>}> <HydrationBoundary state={dehydrate(queryClient)}>
<ContactList contacts={contacts}/> <ContactList/>
</Suspense> </HydrationBoundary>
</nav> </nav>
</div> </div>
<div id={'detail'}> <div id={'detail'}>

View File

@@ -1,11 +1,21 @@
import { getContact, getContacts } from "@/app/data"; import { ContactRecord } from "@/app/data";
export const fetchContacts = async () => { export async function fetchContacts() {
console.log("fetch contacts") console.log("fetchContacts()");
return await getContacts(); 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) => { export async function fetchContact(contactId: string) {
console.log(`fetch contact ${contactId}`) console.log("fetchContacts()");
return await getContact(contactId); 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;
}

View File

@@ -1,12 +1,19 @@
import { ContactRecord } from "@/app/data"; "use client";
import React, { use } from "react";
import Link from "next/link"; 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 <div>Error during prefetch...</div>;
export default function ContactList({ contacts }: { contacts: Promise<ContactRecord[]> }) {
const allContacts = use(contacts);
return ( return (
<ul> <ul>
{allContacts.map((c) => ( {data.map((c) => (
<li key={c.id}> <li key={c.id}>
<Link href={`/contacts/${c.id}`}> <Link href={`/contacts/${c.id}`}>
{c.first || c.last ? ( {c.first || c.last ? (

View File

@@ -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 });
}

View File

@@ -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 });
}

View File

@@ -2,12 +2,16 @@
// 🛑 Nothing in here has anything to do with React Router, it's just a fake database // 🛑 Nothing in here has anything to do with React Router, it's just a fake database
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// noinspection UnnecessaryLocalVariableJS,JSUnusedGlobalSymbols // noinspection UnnecessaryLocalVariableJS,JSUnusedGlobalSymbols
import "server-only" import "server-only";
import { matchSorter } from "match-sorter"; import { matchSorter } from "match-sorter";
// @ts-expect-error - no types, but it's a tiny function // @ts-expect-error - no types, but it's a tiny function
import sortBy from "sort-by"; import sortBy from "sort-by";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { Low } from "lowdb";
import { JSONFile } from "lowdb/node";
import { join } from "path";
import { mkdir } from "fs/promises";
type ContactMutation = { type ContactMutation = {
id?: string; id?: string;
@@ -24,42 +28,97 @@ export type ContactRecord = ContactMutation & {
createdAt: string; createdAt: string;
}; };
//////////////////////////////////////////////////////////////////////////////// // Define the database schema
// This is just a fake DB table. In a real app you'd be talking to a real db or type Schema = {
// fetching from an existing API. records: Record<string, ContactRecord>;
const fakeContacts = { };
records: {} as Record<string, ContactRecord>,
// Set up lowdb
const initDb = async (): Promise<Low<Schema>> => {
// Ensure the db directory exists
const dbDir = join(process.cwd(), '.db');
await mkdir(dbDir, { recursive: true });
const file = join(dbDir, 'contacts.json');
const adapter = new JSONFile<Schema>(file);
const defaultData: Schema = { records: {} };
const db = new Low<Schema>(adapter, defaultData);
// Load existing data
await db.read();
// Initialize if needed
if (!db.data) {
db.data = defaultData;
}
return db;
};
// Create a singleton instance of the database
let dbPromise: Promise<Low<Schema>> | null = null;
const getDb = () => {
if (!dbPromise) {
dbPromise = initDb();
}
return dbPromise;
};
////////////////////////////////////////////////////////////////////////////////
// This is a DB wrapper using lowdb for persistence
const fakeContacts = {
async getAll(): Promise<ContactRecord[]> { async getAll(): Promise<ContactRecord[]> {
return Object.keys(fakeContacts.records) const db = await getDb();
.map((key) => fakeContacts.records[key]) return Object.keys(db.data.records)
.map((key) => db.data.records[key])
.sort(sortBy("-createdAt", "last")); .sort(sortBy("-createdAt", "last"));
}, },
async get(id: string): Promise<ContactRecord | null> { async get(id: string): Promise<ContactRecord | null> {
return fakeContacts.records[id] || null; const db = await getDb();
return db.data.records[id] || null;
}, },
async create(values: ContactMutation): Promise<ContactRecord> { async create(values: ContactMutation): Promise<ContactRecord> {
const db = await getDb();
const id = values.id || Math.random().toString(36).substring(2, 9); const id = values.id || Math.random().toString(36).substring(2, 9);
const createdAt = new Date().toISOString(); const createdAt = new Date().toISOString();
const newContact = { id, createdAt, ...values }; const newContact = { id, createdAt, ...values };
fakeContacts.records[id] = newContact; db.data.records[id] = newContact;
await db.write();
return newContact; return newContact;
}, },
async set(id: string, values: ContactMutation): Promise<ContactRecord> { async set(id: string, values: ContactMutation): Promise<ContactRecord> {
const contact = await fakeContacts.get(id); const db = await getDb();
const contact = await this.get(id);
invariant(contact, `No contact found for ${id}`); invariant(contact, `No contact found for ${id}`);
const updatedContact = { ...contact, ...values }; const updatedContact = { ...contact, ...values };
fakeContacts.records[id] = updatedContact; db.data.records[id] = updatedContact;
await db.write();
return updatedContact; return updatedContact;
}, },
destroy(id: string): null { async destroy(id: string): Promise<null> {
delete fakeContacts.records[id]; const db = await getDb();
delete db.data.records[id];
await db.write();
return null; return null;
}, },
// New reset function to restore the initial data
async reset(): Promise<void> {
const db = await getDb();
db.data.records = {};
await db.write();
// Restore initial data
const initialContacts = getInitialContacts();
for (const contact of initialContacts) {
await this.create(contact);
}
}
}; };
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@@ -94,10 +153,18 @@ export async function updateContact(id: string, updates: ContactMutation) {
} }
export async function deleteContact(id: string) { export async function deleteContact(id: string) {
fakeContacts.destroy(id); await fakeContacts.destroy(id);
} }
[ // New function to reset the database to initial state
export async function resetDatabase() {
console.log("RESET DATABASE");
await fakeContacts.reset();
}
// Helper function to get initial contacts data
function getInitialContacts() {
return [
{ {
avatar: avatar:
"https://sessionize.com/image/124e-400o400o2-wHVdAuNaxi8KJrgtN3ZKci.jpg", "https://sessionize.com/image/124e-400o400o2-wHVdAuNaxi8KJrgtN3ZKci.jpg",
@@ -310,12 +377,19 @@ export async function deleteContact(id: string) {
last: "Jensen", last: "Jensen",
twitter: "@jenseng", twitter: "@jenseng",
}, },
].forEach((contact) => { ].map(contact => ({
fakeContacts.create({
...contact, ...contact,
id: `${contact.first id: `${contact.first
.toLowerCase() .toLowerCase()
.split(" ") .split(" ")
.join("_")}-${contact.last.toLocaleLowerCase()}`, .join("_")}-${contact.last.toLowerCase()}`,
}); }));
}); }
// Initialize with seed data on first load
(async () => {
const db = await getDb();
if (Object.keys(db.data.records).length === 0) {
await resetDatabase();
}
})();

View File

@@ -2,6 +2,7 @@ import React from "react";
import type { Metadata } from "next"; import type { Metadata } from "next";
import "./globals.css"; import "./globals.css";
import Providers from "@/app/providers";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Next.js Address Book", title: "Next.js Address Book",
@@ -16,7 +17,7 @@ export default function RootLayout({
return ( return (
<html lang="en"> <html lang="en">
<body> <body>
{children} <Providers>{children}</Providers>
</body> </body>
</html> </html>
); );

49
src/app/providers.tsx Normal file
View File

@@ -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 (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}