Creating a custom Hook to make requests using React + Axios + TypeScript

Danilo Rivera
3 min readJun 16, 2023

--

We will always need to make calls for our project, so it’s good to have this logic that will be repeated a lot in a Hook. This will allow us to save time and be efficient when making our requests.

For that, we based on GraphQL, , we destructure useQuery and obtain 3 values: data, loading, and error. We will follow this same structure where our hook will be passed a URL, optionally parameters (like timeout), and it will return the same 3 aforementioned states.

GraphQL Example

As dependencies, we will only need

yarn add axios

Remember that your project must have TypeScript installed

First, we will create our hook. useApiHook

This useApiHook hook uses the data, loading, and error states to manage the API call's status. It receives the URL of the endpoint as a parameter and utilizes Axios to make the GET request.

Maybe you’re wondering what the type T means in useState.

In the declaration useState<T>(initialState: T), T is used to specify the type of the state that will be stored and returned. The useState function will receive an initial value of the specified type (initialState: T) and return a tuple containing the current state and a function to update the state."

The use of generic types like T in TypeScript provides flexibility by allowing us to work with different data types safely and without repeating code.

For the test, we will use JSONPlaceholder, specifically the “posts” endpoint. Therefore, we will create a type based on the response from this endpoint and pass it to the hook. We will also pass a URL as a parameter and an optional parameter as an example. As you can see, the implementation is very similar to GraphQL.

Here is an example of how it works:

Here is another example for a failed request:

and as always here I leave the link of the complete code

--

--