useCustom to fetch data on component load
I am trying to fetch data from api using useCustom hook but api is calling multiple times on component render. I can't add useCustom in useEffect since it violates react hook rules. How to call the api once when the component renders using useCustom?
3 Replies
Hi @anishkumar6701. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
The
useCustom
hook from refine is designed to trigger a new request when its properties are changed. This behavior is similar to how the useEffect
hook works in React. If your API is being called multiple times, it might be due to changes in the properties you're passing to useCustom
.
To ensure that the API is called only once when the component renders, you need to make sure that the properties you're passing to useCustom
are not changing after the initial render. This includes the url
, method
, and config
properties.
Here's an example of how to use the useCustom
hook:
In this example, the useCustom
hook will only trigger a new request if apiUrl
, method
, or config
changes. If these values remain constant across renders, the API will only be called once.
If you're passing dynamic values to useCustom
and you want to prevent unnecessary API calls, you might need to implement some form of state management or memoization to ensure that these values don't change unnecessarily.
For more information, you can refer to the useCustom documentation (https://refine.dev/docs/api-reference/core/hooks/data/useCustom/).
----------------------
Note: you can ask me a follow up question by @ mentioning me again
:speech_balloon:
----------------------<@1087038083872080003> kapa.ai is still learning and improving, please let us know how it did by reacting below
fascinating-indigo•14mo ago
Hey @anishkumar6701,
It may caused from React.StrictMode. You can checkout this: https://refine.dev/docs/faq/#why-are-api-calls-triggering-twice