Skip to content

Commit

Permalink
just adding useCMS and the test for it back in for now so the linter …
Browse files Browse the repository at this point in the history
…will stop screaming
  • Loading branch information
Stephen Swanson authored and Stephen Swanson committed Jul 22, 2024
1 parent fc5507a commit 376bb6b
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
36 changes: 36 additions & 0 deletions hooks/useCMS.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
52 changes: 52 additions & 0 deletions hooks/useCMS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// This is not currently in a working state

import { useState, useEffect } from "react";

interface DirectusResponse<T> {
data: T;
meta: any;
}

interface UseCMSProps<T> {
collection: string;
query?: string;
initialData?: T;
}

const useCMS = <T>({ collection, query = "", initialData }: UseCMSProps<T>) => {
const [data, setData] = useState<T | null>(initialData || null);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(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<T> = 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;

0 comments on commit 376bb6b

Please sign in to comment.