T
TanStack3y ago
stormy-gold

Enable query on click and get updated data in same function

3 Replies
stormy-gold
stormy-goldOP3y ago
const { data, refetch, isFetching } = useQuery({
queryKey: ["todos"],
queryFn: async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
const data = await res.json();
return data;
},
enabled: false
});
const handleClick = async () => {
await refetch();
if (data) {
alert(data[0].title);
}
};
const { data, refetch, isFetching } = useQuery({
queryKey: ["todos"],
queryFn: async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
const data = await res.json();
return data;
},
enabled: false
});
const handleClick = async () => {
await refetch();
if (data) {
alert(data[0].title);
}
};
how can I get data in after refetch
extended-salmon
extended-salmon3y ago
refetch return type is Promise<UseQueryResult>. So you can do:
const result = await refetch();
if (result.data) {
alert(result.data[0].title);
}
const result = await refetch();
if (result.data) {
alert(result.data[0].title);
}
I don't know what the end goal is but instead of calling refetch() I would probably look into setting enabled to true and using the data returned by useQuery though.
stormy-gold
stormy-goldOP3y ago
I am getting data, I am not setting any query params to enable query based on params so I an refetching on click. after fetch I want to make a custom logic in the function

Did you find this page helpful?