Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

1.6 KB
Raw Blame
import { useRouterStuff } from "@dub/ui";
import { fetcher } from "@dub/utils";
import useSWR, { SWRConfiguration } from "swr";
import * as z from "zod/v4";
import { ExpandedLinkProps, UserProps } from "../types";
import { getLinksQuerySchemaExtended } from "../zod/schemas/links";
import useWorkspace from "./use-workspace";

const partialQuerySchema = getLinksQuerySchemaExtended.partial();

export default function useLinks(
  opts: z.infer<typeof partialQuerySchema> = {},
  swrOpts: SWRConfiguration = {},
) {
  const { id: workspaceId, isMegaWorkspace } = useWorkspace();
  const { getQueryString } = useRouterStuff();

  const {
    data: links,
    isValidating,
    error,
  } = useSWR<
    (ExpandedLinkProps & {
      user: UserProps;
    })[]
  >(
    workspaceId
      ? `/api/links${getQueryString(
          {
            workspaceId,
            includeUser: "true",
            includeDashboard: "true",
            ...opts,
            // don't show archived on mega workspaces
            ...(isMegaWorkspace
              ? {
                  showArchived: "false",
                }
              : {}),
          },
          {
            include: [
              "folderId",
              "tagIds",
              "domain",
              "userId",
              "search",
              "page",
              "sortBy",
              "sortOrder",
              "showArchived",
            ],
          },
        )}`
      : null,
    fetcher,
    {
      dedupingInterval: 20000,
      revalidateOnFocus: false,
      keepPreviousData: true,
      ...swrOpts,
    },
  );

  return {
    links,
    isValidating,
    error,
  };
}