Reputation: 17
I'm using TanStack Query (React Query) to fetch data in my React application. I have the following code in my Home component:
This is a educational project im working on to practice this package.
export default function Home() {
const query = useQuery({
queryKey: ['auth-user', 1],
queryFn: fetch('http://localhost/api/user').then(res => res.json()).catch(err => err.response),
// staleTime: 10000,
// enabled: false,
// retry: false
});
return (
<>
<Navbar />
<HeaderSection />
<Footer />
</>
);
}
The issue I'm facing is that the API call to http://localhost/api/user gets called multiple times on page load, even though I've set staleTime to 10000 milliseconds (10 seconds).
However, when I set enabled to false, the API call is triggered only once, which is the expected behavior.
I noticed that this issue occurs only when the API call fails. I tried disabling retries by setting retry to false, which reduced the number of times the API call was made, but it still gets called twice on page load.
Can someone explain why the staleTime option is not working as expected, and the API call is being fired multiple times on page load, especially when the API call fails?
Additional Information:
Any help or guidance on resolving this issue would be greatly appreciated.
Upvotes: 0
Views: 3220
Reputation: 395
The problem is that in the code provided there is returning of the Promise res.json(). The correct code is:
const query = useQuery({
queryKey: ["homes"],
queryFn: fetch("http://127.0.0.1:5000/homes")
.then((res) => {
console.log("request executed")
res.json()
})
.then((json) => {
return json
})
.catch((err) => err.response),
});
useQuery needs the json/data, which comes from the Promise res.json(), not the Promise itself.
EDIT: I saw edited question from the OP - the version of react-query is v3.x
The working code for this is:
import { useQuery } from "react-query";
const fetchHomes = async () => {
const resp = await fetch("http://127.0.0.1:5000/homes");
console.log("fetched")
if (!resp.ok) {
throw new Error("Network response was not ok");
}
return resp.json();
};
export default function Home() {
const query = useQuery("homes", fetchHomes)
return <p>Some paragraph</p>;
}
Upvotes: 0