김정수
김정수

Reputation: 841

How to call API only once with React Query?

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
}

Upvotes: 7

Views: 25123

Answers (1)

Gerardo Sabetta
Gerardo Sabetta

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:

  • 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

Upvotes: 15

Related Questions