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,
|
|
|
|
searchFilter,
|
|
|
|
searchQuery,
|
|
|
|
pinnedOnly,
|
|
|
|
collectionId,
|
|
|
|
tagId,
|
|
|
|
}: Omit<LinkRequestQuery, "cursor"> = { sort: 0 }
|
|
|
|
) {
|
2023-06-14 17:34:54 -05:00
|
|
|
const { links, setLinks, resetLinks } = useLinkStore();
|
|
|
|
const router = useRouter();
|
|
|
|
|
|
|
|
const hasReachedBottom = useDetectPageBottom();
|
|
|
|
|
|
|
|
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
|
2023-06-15 07:39:30 -05:00
|
|
|
const requestBody: LinkRequestQuery = {
|
|
|
|
cursor,
|
|
|
|
sort,
|
|
|
|
searchFilter,
|
|
|
|
searchQuery,
|
|
|
|
pinnedOnly,
|
|
|
|
collectionId,
|
|
|
|
tagId,
|
|
|
|
};
|
|
|
|
|
|
|
|
const encodedData = encodeURIComponent(JSON.stringify(requestBody));
|
|
|
|
|
2023-06-14 17:34:54 -05:00
|
|
|
const response = await fetch(
|
2023-06-15 07:39:30 -05:00
|
|
|
`/api/routes/links?body=${encodeURIComponent(encodedData)}`
|
2023-06-14 17:34:54 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok) setLinks(data.response, isInitialCall);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
resetLinks();
|
|
|
|
|
|
|
|
getLinks(true);
|
|
|
|
}, [router, sort, searchFilter]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (hasReachedBottom) getLinks(false, links?.at(-1)?.id);
|
|
|
|
}, [hasReachedBottom]);
|
|
|
|
}
|