Vue 3 Tanstack query with params data not being fetched

62 Views Asked by At

Hi everyone could anyone help me with Vue3 Tanstack Query usage I've went through the docs and tried applying data refetch on parameter change but for some reason the api call is not being triggered... Any ideas?

<script lang="ts" setup>
import { fetchEnergyData } from "@/queries/useEnergyQuery";
import { useQuery } from "@tanstack/vue-query";
import { ref } from "vue";

type DateRange = {
  start: Date;
  end: Date;
};

const date = ref<DateRange>({
  start: new Date(2022, 0, 20),
  end: addDays(new Date(2022, 0, 20), 20),
});

const getDateString = (date: Date | undefined): string | undefined => {
  if (!date) return;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  const formattedDate = ${year}-${month}-${day};
  return formattedDate;
};

const { data, isLoading, isError } = useQuery({
  queryKey: ["energyData", date.value.start, date.value.end],
  queryFn: () =>
    fetchEnergyData(
      getDateString(date.value.start),
      getDateString(date.value.end),
    ),
});
</script>
1

There are 1 best solutions below

0
Mickael Oth On

To ensure your queryKey array triggers a refetch on params changes, it needs to have reactive value(s) and currently, you only have 3 static values.

In your case, you could simply use your date ref or wrap date.value.start and date.value.end in computed values if you prefer to maintain those specific keys.

Therefore, it would end up being something as follows:

const startDate = computed<Date>(() => date.value.start);
const endDate = computed<Date>(() => date.value.end);

const { data, isLoading, isError } = useQuery({
  queryKey: ["energyData", startDate, endDate],
  queryFn: () =>
    fetchEnergyData(
      getDateString(date.value.start),
      getDateString(date.value.end),
    ),
});