I need some help with a code

  let id = $derived(data.id);
  let authToken = ...

  let getAllBetsBySheetIdQuery = useGetAllBetsBySheetId({
    id,
    authToken
  });
  let { data: bets } = $derived(getAllBetsBySheetIdQuery);


import { BASE_URL } from "$lib/apiutils";
import { PlacedBetsSchema } from "$lib/types";
import { createQuery } from "@tanstack/svelte-query";
import { z } from "zod";

const GetAllBetsBySheetIdRequestSchema = z.object({
  id: z.string(),
  authToken: z.string()
});

type GetAllBetsBySheetIdRequest = z.infer<typeof GetAllBetsBySheetIdRequestSchema>;

export async function getAllBetsBySheetId(req: GetAllBetsBySheetIdRequest) {
  const response = await fetch(`${BASE_URL}/placed-bets/${req.id}`, {
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + req.authToken
    }
  });

  if (!response.ok) {
    throw Error("error");
  }

  const r = await response.json();
  const bets = PlacedBetsSchema.parse(r.bets);
  return bets;
}

export function useGetAllBetsBySheetId(req: GetAllBetsBySheetIdRequest) {
  return createQuery(() => ({
    queryKey: ["bets", req.id, "all"],
    queryFn: () => getAllBetsBySheetId(req),
  }));
}


The problem I am getting is that, in the first code snippet, the reference to "id" only captures the initial state of id, if my id changes, it is not reactive. The solution would be wrapping the "useGetAllBetsBySheetId" on a "$derived(...)" rune, however, for TanStack Query, it does not work that way, it actually causes an infinite loop of requests (see here. What do I do in this situation in order to make my code work?

I am using SvelteKit 5 and the port to Svelte 5 for TanStack Query (not released yet).
Was this page helpful?