'React Query "Fetching" state but not sending request to server
I'm having a recurrent problem with react query. On some queries, the query says "fetching" (blue color), but the request to the server "doesn't go through". It's "suspended" or something. And I tried console.logging on my nodeJS controller (associated with the GET endpoint), but the function isn't even called.
This is quite annoying (and to be clear, this is with new queries which aren't stale or cached).
This is my query:
const postDetails = useQuery(
["post", postId],
async () =>
await fetch(
"http://localhost:5000/api/post/id/" + postId
).then((res) => res.json()),
{
onSuccess: (data) => {
console.log(data);
},
}
);
This is what React Query Devtools says:
This is what the network tab says:
Thanks in advance.
Solution 1:[1]
I believe your use of await and .then is giving you issues. I would recommend just sticking with await
const postDetails = useQuery(
["post", postId],
async () =>
try {
let res = await fetch(
"http://localhost:5000/api/post/id/" + postId
)
res = await res.json()
} catch(err) {
console.error(err)
}
{
onSuccess: (data) => {
console.log(data);
},
}
);
This method uses a trycatch for error handling, and does not rely on .then which I believe is where the issue lies.
Solution 2:[2]
Try separating the fetch function from the query:
async function fetchPosts() {
try {
const res = await fetch(
"http://localhost:5000/api/post/id/" + postId
)
const json = await res.json()
return json
} catch (err) {
console.error(err)
}
}
const postDetails = useQuery(
["post", postId],
fetchPosts,
{
onSuccess: (data) => {
console.log(data);
},
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ask4you |


