Reputation: 841
I'm making a visitor call system with React Query.
I have a kind of call (button) and I want to call the api only when it is pressed. However, when the component is rendered, it keeps calling the api.
What should I do?
//App.jsx
const query = useQuery('resData', getEmployData('datas'), {
enabled: false
});
const callBtn = () => {
query.refetch()
}
return (
<ul>
<li onClick ={callBtn}>Post</li>
<li>Food</li>
<li>Other</li>
</ul>
)
this is api function
const getEmployData = async(callKind) => {
const {data} = await axios.get(`${baseUrl}/welcome?callKind=${callKind}`);
return data
}
Upvotes: 7
Views: 25123
Reputation: 559
You can achieve that by using staleTime: Infinity
on your config object. Please take a look at https://tanstack.com/query/v4/docs/react/guides/initial-query-data#staletime-and-initialdataupdatedat
Your code should look like:
const query = useQuery('resData', getEmployData('datas'), {
enabled: false,
staleTime: Infinity
});
This will tell react query that this data should be considered as "Fresh", by default queries are marked as "Stale" right away and "Stale" queries are refetched automatically in the background when:
https://tanstack.com/query/v3/docs/react/guides/important-defaults
Upvotes: 15