From 376bb6bdaed0a2fa195bf850db74036a3362b911 Mon Sep 17 00:00:00 2001 From: Stephen Swanson Date: Mon, 22 Jul 2024 20:45:49 +0300 Subject: [PATCH] just adding useCMS and the test for it back in for now so the linter will stop screaming --- hooks/useCMS.test.ts | 36 ++++++++++++++++++++++++++++++ hooks/useCMS.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 hooks/useCMS.test.ts create mode 100644 hooks/useCMS.ts diff --git a/hooks/useCMS.test.ts b/hooks/useCMS.test.ts new file mode 100644 index 0000000..59abf31 --- /dev/null +++ b/hooks/useCMS.test.ts @@ -0,0 +1,36 @@ +import { expect, test, vi } from "vitest"; +import useCMS from "./useCMS"; +import { renderHook } from "@testing-library/react"; + +test("calls fetch", () => { + const fetchMock = vi.spyOn(global, "fetch"); + + renderHook(() => useCMS({ collection: "text" })); + + expect(fetchMock).toHaveBeenCalled(); +}); + +test("does not call fetch on rerender", () => { + const fetchMock = vi.spyOn(global, "fetch"); + + const { rerender } = renderHook(() => useCMS({ collection: "text" })); + rerender(); + + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +test.skip("calls fetch once for the same collection", () => { + const fetchMock = vi.spyOn(global, "fetch"); + + renderHook(() => useCMS({ collection: "text" })); + renderHook(() => useCMS({ collection: "text" })); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +test("calls fetch once per collection", () => { + const fetchMock = vi.spyOn(global, "fetch"); + + renderHook(() => useCMS({ collection: "text" })); + renderHook(() => useCMS({ collection: "image" })); + expect(fetchMock).toHaveBeenCalledTimes(2); +}); diff --git a/hooks/useCMS.ts b/hooks/useCMS.ts new file mode 100644 index 0000000..9422d70 --- /dev/null +++ b/hooks/useCMS.ts @@ -0,0 +1,52 @@ +// This is not currently in a working state + +import { useState, useEffect } from "react"; + +interface DirectusResponse { + data: T; + meta: any; +} + +interface UseCMSProps { + collection: string; + query?: string; + initialData?: T; +} + +const useCMS = ({ collection, query = "", initialData }: UseCMSProps) => { + const [data, setData] = useState(initialData || null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + const fetchData = async () => { + setLoading(true); + setError(null); + + try { + const response = await fetch( + `${process.env.NEXT_PUBLIC_DIRECTUS_URL}/items/text`, + ); + if (!response.ok) { + throw new Error(`Error: ${response.status} ${response.statusText}`); + } + const result: DirectusResponse = await response.json(); + setData(result.data); + } catch (err) { + if (err instanceof Error) { + setError(err.message); + } else { + setError("An unknown error occurred"); + } + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [collection, query]); + + return { data, loading, error }; +}; + +export default useCMS;