TanStackT
TanStack2mo ago
23 replies
brilliant-lime

Simpler parametrization of query collections

Hi, it's great that predicate push-down enables some parametrization of queries, but could the API be made simpler and more typesafe? For example, for a pretty simple use-case, I have to write quite a bit of code, none of which is typesafe

const accountIdsCollection = createCollection(
  queryCollectionOptions({
    syncMode: "on-demand",
    queryKey: ["account", "id"],
    queryFn: () => fetch("/api/my/accounts").then((r) => r.json()),
    getKey: (data) => data.externalId,
    queryClient,
  })
);

const accountsDataCollection = createCollection(
  queryCollectionOptions({
    syncMode: "on-demand",
    queryKey: ["account", "data"],
    queryFn: ({ meta }) => {
      const ids = parseLoadSubsetOptions(meta?.loadSubsetOptions).filters.find(
        ({ operator, field }) =>
          operator === "in" && field.length === 1 && field[0] === "externalId"
      )?.value;

      if (!ids) throw new Error("No ids found");

      const params = new URLSearchParams({ ids: ids.join(",") });

      return fetch(`https://external.abc/api/?${params}`).then((r) => r.json());
    },
    getKey: (data) => data.accountId,
    queryClient,
  })
);

createCollection(
  liveQueryCollectionOptions({
    query: (q) =>
      q
        .from({ account: accountIdsCollection })
        .join(
          { data: accountsDataCollection },
          ({ account, data }) => eq(account.externalId, data.accountId),
          "left"
        ),
    startSync: true,
  })
);
Was this page helpful?