const useFetchPosts = (params?: Record<string, string>) => {
async function fetchPosts({
queryKey,
}: {
queryKey: [string, Record<string, string> | undefined];
}) {
const [, params] = queryKey;
let url = new URL("http://localhost:8080/api/post");
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (key === "category") {
url = new URL("http://localhost:8080/api/post/category");
} else {
url = new URL("http://localhost:8080/api/post/search");
}
url.searchParams.append(key, value);
});
}
const response = await fetch(url, { credentials: "include" });
if (!response.ok) throw new Error("Network response was not ok");
return response.json();
}
const { status, data, error } = useQuery({
queryKey: ["posts", params],
queryFn: fetchPosts,
staleTime: Infinity,
});
return { status, data, error };
};
const useFetchPosts = (params?: Record<string, string>) => {
async function fetchPosts({
queryKey,
}: {
queryKey: [string, Record<string, string> | undefined];
}) {
const [, params] = queryKey;
let url = new URL("http://localhost:8080/api/post");
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (key === "category") {
url = new URL("http://localhost:8080/api/post/category");
} else {
url = new URL("http://localhost:8080/api/post/search");
}
url.searchParams.append(key, value);
});
}
const response = await fetch(url, { credentials: "include" });
if (!response.ok) throw new Error("Network response was not ok");
return response.json();
}
const { status, data, error } = useQuery({
queryKey: ["posts", params],
queryFn: fetchPosts,
staleTime: Infinity,
});
return { status, data, error };
};