DEV Community

Cover image for Why using AXIOS with Typescript?
limacodes
limacodes

Posted on

Why using AXIOS with Typescript?

I want to explore on this post about working with API using typescript by comparing fetch to axis BUT focusing on productivity

First thing first. Do you know how axios works and how it can be compared to fetch? 

well…in chatgpt times we don't need to search so much for an straight answer right?

I want you to follow the right questions path and bare with me on the most important ones. What is best for your company vs productivity when you work with requests that needs different approaches for testing, debugging, error handling etc. Are you the decision maker or the order taker?
So lets do this…

Considering that Axios is a JavaScript library used to make HTTP requests from the browser or a Node.js server. It is similar to the fetch API, but it offers a more powerful and flexible way of making HTTP requests.

Axios works by creating a new instance of the Axios client and using its methods, such as get() or post(), to make the desired HTTP request. The response from the server is returned as a Promise that can be processed using then() and catch() methods. Like:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

So, compared to the fetch API, Axios has several advantages like converting the response to JSON, which makes it easier to work with. It also has a built-in mechanism for handling errors, which makes it less error-prone than fetch. 

Axios also allows you to configure default settings, such as headers, which are applied to all requests, making it easier to work with APIs that require authentication or other specific settings.

When it comes to making HTTP requests in JavaScript, Axios and fetch are two popular options. While both have their advantages, there are several productivity benefits to using Axios over fetch.

While both have their advantages, Axios can be a better option for developers who need a more powerful and flexible solution for making HTTP requests.

Use a typed API client library such as axios-typed-isomorphic or apisauce-ts instead of the built-in fetch function when working with APIs in TypeScript. These libraries provide a more type-safe and user-friendly way of making HTTP requests and handling responses.

import axios from 'axios-typed-isomorphic'

interface User {
  id: number
  name: string
}

const getUsers = async (): Promise<User[]> => {
  const { data } = await axios.get<User[]>('https://my-api.com/users')
  return data
}
Enter fullscreen mode Exit fullscreen mode

Always define interfaces for the data types that your API is expected to return, and use them to type-check the response data. This will help you catch any errors early on and make your code more maintainable.

interface User {
  id: number
  name: string
}

interface ApiResponse {
  data: User[]
  status: number
}

const getUsers = async (): Promise<ApiResponse> => {
  const { data } = await axios.get<ApiResponse>('https://my-api.com/users')
  return data
}
Enter fullscreen mode Exit fullscreen mode

Follow best practices for error handling when working with APIs in TypeScript. For example, use try-catch blocks to handle errors that may occur during the request-response cycle, and return appropriate error codes or messages to the user.
Additionally, it's a good idea to use a centralized error-handling middleware for your application to handle errors in a consistent way across different parts of your application.

interface User {
  id: number
  name: string
}

interface ApiResponse {
  data: User[]
  status: number
}

interface ApiError {
  message: string
  status: number
}

const getUsers = async (): Promise<ApiResponse | ApiError> => {
  try {
    const { data } = await axios.get<ApiResponse>('https://my-api.com/users')
    return data
  } catch (error) {
    return {
      message: error.message,
      status: error.response.status
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Overall, using a typed API client library like axios-typed-isomorphic or apisauce-ts and following best practices for error handling will help you write more robust and maintainable code when working with APIs in TypeScript.

First, Axios has a more user-friendly API. It automatically converts the response to JSON and has built-in mechanisms for handling errors, making it easier to work with and less prone to bugs. This can result in faster development times and less time spent debugging.

Second, Axios allows developers to configure default settings, such as headers, which are applied to all requests. This can make it easier to work with APIs that require authentication or other specific settings. This can save time and reduce the chance of mistakes when making multiple requests to the same API.

Third, Axios has a large and active community of developers, which can be a valuable resource for troubleshooting and finding solutions to common problems. This can result in faster resolution times and increased productivity.

In conclusion, while both Axios and fetch have their advantages, the user-friendly API, ability to configure default settings, and large developer community make Axios a more productive option for tech companies.

These benefits can result in faster development times, reduced errors, and increased efficiency, making Axios a great choice for companies looking to improve their tech processes.

Just sharing my thoughts for whom it might concern

Top comments (2)

Collapse
 
grisho4ek profile image
Grygorii Shevchenko • Edited

In my opinion the main advantage of using axios is interceptors. They are very useful for refreshing token and updating an authorization header before sending requests to api endpoints and also they can be used for error handling.

Collapse
 
limacodes profile image
limacodes

Thank you for your input :) You are correct, axios does indeed have a great feature in the form of interceptors. And you're also right about the ease of error handling with interceptors for sure.
Yeah Axios is a powerful tool for handling HTTP requests in the frontend.
Great point