7

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.

  1. How not to call the component when it is rendered
  2. How to call api only when button is pressed

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
}

1 Answer 1

15

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:

  • New instances of the query mount
  • The window is refocused
  • The network is reconnected.
  • The query is optionally configured with a refetch interval.

https://tanstack.com/query/v3/docs/react/guides/important-defaults

Sign up to request clarification or add additional context in comments.

5 Comments

If the query fails, it will retry in this case?
By default React query will retry a failing request up to 3 times before settling on status errored. Whether the request ends up in status: "success" or status: "error" makes no difference to the freshness or staleness of the data. If the request is a status: "error" and it's considered "fresh", it will behave exactly as a status: "success" would do.
So you'll need retry: falseto guarantee that it will only call API once.
Correct, I always disable retryability in react-query, you can disable it globally using the QueryClient defaultOptions parameters tanstack.com/query/v4/docs/reference/QueryClient
saved my day! spent hours finding where it's triggering the render 💀

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.