el.xwx.moe/hooks/useLinks.tsx

96 lines
2.4 KiB
TypeScript
Raw Normal View History

import { LinkRequestQuery } from "@/types/global";
import { useEffect } from "react";
import useDetectPageBottom from "./useDetectPageBottom";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
2023-06-15 07:39:30 -05:00
export default function useLinks(
{
sort,
collectionId,
tagId,
2023-10-23 09:45:48 -05:00
pinnedOnly,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
searchByTags,
2023-11-01 05:01:26 -05:00
searchByTextContent,
2023-08-30 23:00:57 -05:00
}: LinkRequestQuery = { sort: 0 }
2023-06-15 07:39:30 -05:00
) {
2024-02-11 01:29:11 -06:00
const { links, setLinks, resetLinks, selectedLinks, setSelectedLinks } =
useLinkStore();
const router = useRouter();
const { reachedBottom, setReachedBottom } = useDetectPageBottom();
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
2023-10-23 09:45:48 -05:00
const params = {
2023-06-15 07:39:30 -05:00
sort,
2023-10-23 09:45:48 -05:00
cursor,
2023-06-15 07:39:30 -05:00
collectionId,
tagId,
2023-10-23 09:45:48 -05:00
pinnedOnly,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
searchByTags,
2023-11-01 05:01:26 -05:00
searchByTextContent,
2023-10-23 09:45:48 -05:00
};
const buildQueryString = (params: LinkRequestQuery) => {
return Object.keys(params)
.filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
.map(
(key) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
params[key as keyof LinkRequestQuery] as string
)}`
)
.join("&");
2023-06-15 07:39:30 -05:00
};
2023-11-15 12:12:06 -06:00
let queryString = buildQueryString(params);
2023-06-15 07:39:30 -05:00
2023-11-15 12:12:06 -06:00
let basePath;
if (router.pathname === "/dashboard") basePath = "/api/v1/dashboard";
else if (router.pathname.startsWith("/public/collections/[id]")) {
queryString = queryString + "&collectionId=" + router.query.id;
basePath = "/api/v1/public/collections/links";
} else basePath = "/api/v1/links";
const response = await fetch(`${basePath}?${queryString}`);
const data = await response.json();
if (response.ok) setLinks(data.response, isInitialCall);
};
useEffect(() => {
// Save the selected links before resetting the links
// and then restore the selected links after resetting the links
2024-02-11 01:29:11 -06:00
const previouslySelected = selectedLinks;
resetLinks();
setSelectedLinks(previouslySelected);
getLinks(true);
2023-10-23 09:45:48 -05:00
}, [
router,
sort,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
2023-11-01 05:01:26 -05:00
searchByTextContent,
2023-10-23 09:45:48 -05:00
searchByTags,
]);
useEffect(() => {
if (reachedBottom) getLinks(false, links?.at(-1)?.id);
setReachedBottom(false);
}, [reachedBottom]);
}