How to build a React Hook to make AJAX calls
Today we are going to create a simple hook that helps me everyday in my React projects, both web and react-native: a hook to make Ajax Calls and that returns the response.
For testing the hook, we are going to build a simple app that will display all the Houses of Game Of Thrones, provided by https://www.anapioficeandfire.com.
To summarise, this is what we are going to do in this article:
- create a new React Hook
- this Hook will accept an URL to fetch and a series of options (queries, method and body)
- this Hook will return an object with the AJAX response and a loading and error boolean values
- Every time one of the options given to the hook is changed, the Hook will fetch again the URL
- create a demo app to test this useFetch Hook
First, let’s create the skeleton app ☠️
I think I made this step 300 times in the past years, but I always find myself googling the correct command to use with create-react-app. I think I have some sort of selective forgetfulness for this simple command… so this part is more for the future me than for you :)