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>
To ensure your
queryKeyarray 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
dateref or wrapdate.value.startanddate.value.endin computed values if you prefer to maintain those specific keys.Therefore, it would end up being something as follows: