T
TanStack2y ago
stormy-gold

Vue 3 setup API Tanstack Query with params not refetching data

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>
<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>
4 Replies
stormy-gold
stormy-goldOP2y ago
Even if I wrap date ref with computed property the issue is still the same the date has correct values but new API call is not being made
rising-crimson
rising-crimson2y ago
You're losing reactivity in your queryKey, by unwrapping it with .value access. Change that to queryKey: ["energy", date], so that vue-query can detect that value of date ref has changed. Also not sure if it's just a typo here but you're not returning fetchEnergyData promise in queryFn.
stormy-gold
stormy-goldOP2y ago
yes you are right about query key I had to remove .value... Not sure why though since the value property is being changed. queryFn is an arrow function so I don't need to return it?
fascinating-indigo
fascinating-indigo2y ago
There's no compiler magic happening with Vue query so it has no way of tracking the .value changing so you have to pass a ref or wrap the whole thing in computed()

Did you find this page helpful?