I’m using useQuery inside a custom hook, called usePostData. this is the custom hook code:
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
const usePostData = (queryKey, endPoint, object) =>
useQuery(
[queryKey],
async () => {
await axios
.post("http://localhost:1337" + endPoint, object)
.then((data) => console.log(data, queryKey))
.catch((err) => console.log(err));
return data;
},
{ enabled: false }
);
export default usePostData;
I’m calling it on a submit event of a form, like this:
const { data: response, refetch } = usePostData(
`postSingularExpense-${Math.random()}`,
"/api/expences",
submittedExpense
);
const handleSubmitExpense = async (e) => {
e.preventDefault();
await refetch();
};
for some reason, it runs 4 times instead of once and thenm stops with this error message:
why is that and how to correct it?
2
Answers
data
outside of the function where it existsawait axios.post().then()
doesn’t make sense. If you’re usingawait
on a function, it will return resolved value so you don’t need.then()
. Useasync/await
or promise syntax, not both 🙂Also, I noticed your query key:
postSingularExpense-${Math.random()}
. What is that? If you want to force a refetch you should’t need to randomize the key.useQuery()
returns functionretry()
and includes options likerefetchOnMount
,refetchInterval
etc. You should look into using one of those approaches instead.The data variable inside your useQuery callback is not defined, (block scope) which leads to the ReferenceError you’re receiving.
Solve it by removing the
await
and.then()
s 🙂You need to capture the response data returned by the POST request and return it from the callback function.
In addition, you’re generating a random query key for each request, which causes a new query to be created every time. Instead, you should use a better, more stable, query key, such as the endpoint or a unique identifier for the resource you’re posting.
The updated code is:
Hope you find this helpful!