Home > Blockchain >  Custom Hooks for Axios
Custom Hooks for Axios

Time:03-31

I have made a custom hook (called useApi) over axios call. This custom takes api endpoint(url) and method type as input and return the data as mentioned below:

const [ data, fetchError, isLoading ]= useApi(`/users`,'POST');

Now, calling this hook in functional component or useEffect works fine. And as per the rules of hooks

Don’t call Hooks inside loops, conditions, or nested functions.

If I try to call this hook in an event listener, it does not work which is true as per the rules of hook. I can return a method callback and then run it.

I am implementing the frontend architecture of a react-native project and have come to conclusion that only custom hooks will not be enough for api handling and I will need a wrapper for all methods of axios in order to support api integration in my react-native app.

It would be great if anyone can help me with conclusions and help me decide if only custom hooks will work for api integration.

CodePudding user response:

One common pattern is to return a function from your hook, which you can then run anywhere you like. You could use the inputs of your existing hook, and return a get function that executes the axios call. This function can be run inside loops, in useEffect, etc.

Depending on your needs, you might consider the react-query library. It was built as an abstraction layer over API calls, and handles caching, polling, and various other repetitive tasks. I'm sure there are many libraries that cover this territory, but we use react-query in our React Native project and I've enjoyed it so far.

  • Related