2023-06-14 17:34:54 -05:00
|
|
|
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-08-30 23:00:57 -05:00
|
|
|
}: LinkRequestQuery = { sort: 0 }
|
2023-06-15 07:39:30 -05:00
|
|
|
) {
|
2023-06-14 17:34:54 -05:00
|
|
|
const { links, setLinks, resetLinks } = useLinkStore();
|
|
|
|
const router = useRouter();
|
|
|
|
|
2023-10-03 06:04:13 -05:00
|
|
|
const { reachedBottom, setReachedBottom } = useDetectPageBottom();
|
2023-06-14 17:34:54 -05:00
|
|
|
|
|
|
|
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,
|
|
|
|
};
|
|
|
|
|
|
|
|
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-10-23 09:45:48 -05:00
|
|
|
const queryString = buildQueryString(params);
|
2023-06-15 07:39:30 -05:00
|
|
|
|
2023-06-14 17:34:54 -05:00
|
|
|
const response = await fetch(
|
2023-10-23 09:45:48 -05:00
|
|
|
`/api/v1/${
|
|
|
|
router.asPath === "/dashboard" ? "dashboard" : "links"
|
|
|
|
}?${queryString}`
|
2023-06-14 17:34:54 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok) setLinks(data.response, isInitialCall);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
resetLinks();
|
|
|
|
|
|
|
|
getLinks(true);
|
2023-10-23 09:45:48 -05:00
|
|
|
}, [
|
|
|
|
router,
|
|
|
|
sort,
|
|
|
|
searchQueryString,
|
|
|
|
searchByName,
|
|
|
|
searchByUrl,
|
|
|
|
searchByDescription,
|
|
|
|
searchByTags,
|
|
|
|
]);
|
2023-06-14 17:34:54 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
2023-10-03 06:04:13 -05:00
|
|
|
if (reachedBottom) getLinks(false, links?.at(-1)?.id);
|
|
|
|
|
|
|
|
setReachedBottom(false);
|
|
|
|
}, [reachedBottom]);
|
2023-06-14 17:34:54 -05:00
|
|
|
}
|