This code is working weirdly for useQuery. Apparently on the first button click useQuery will not get the updated value of count while the fetcher function gets the updated value (1). I observed that if you move the useEffect below the useQuery function it works fine. Putting the refetch in the dependency array requires putting the useEffect below the useQuery function.
import { useQuery } from "@tanstack/react-query";
function Comp() {
const [count, setCount] = useState(0);
useEffect(() => {
if (count > 0) {
fetcher();
refetch();
}
}, [count]);
const { refetch } = useQuery({
queryKey: ["count", count],
queryFn: async () => {
if (count === 0) {
console.log("ignoring because count =", count);
return "ignore";
}
const result = await fetch("...", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ count }),
});
if (!result.ok) {
throw new Error("Something went wrong");
}
return "ok";
},
enabled: false,
});
const fetcher = async () => {
console.log(count);
try {
const result = await fetch("...", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ count }),
});
if (!result.ok) {
throw new Error("Something went wrong");
}
} catch (e) {
console.error(e);
}
};
return (
<>
<button
onClick={() => {
setCount((prev) => prev + 1);
}}
>
Click
</button>
</>
);
}
Any idea why useQuery works like that? Any idea how to approach this without using Redux etc.? Thanks.