Skip to content

Axios HTTP Go Style

Make your HTTP request simple by using GO style in JavaScript

Rizki Maulana Citra

Created by / Rizki Maulana Citra

Introduction

Are you using Axios to handle your HTTP request? well most of the time you might repeat the method when working with an HTTP request, especially using async / await this GO style will make it simple for you to use HTTP requests.

What is GO? well Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

Read more about Go

Go Style

Error handling in GO is beautiful, let's take a look at this simple example:

GO
import { "net" "net/http" }

func main() {
    content, err := http.Get("https://fizzbuzz.com")

    if(err != nil){
    // handle error here
    }

    // do the rest of your code here if there's no error
}

That's how it works, we know if something goes wrong, if the err value is not a nil that means we got an error then inside the if statement we can handle all the errors.

Implementing in TypeScript

I was going to explain on JavaScript, but I think TypeScript is way better to understand this because GO is a Statically Type Programming Language.

Now let's implement that style in TypeScript. I'm going to use Axios, a small library to work with HTTP.

TS
import axios from 'axios'
import type { AxiosError, AxiosRequestConfig } from 'axios'

type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'

export const http = async <T>(
  method: Method,
  config?: AxiosRequestConfig
): Promise<[T | null, null | AxiosError<T, T>]> => {
  try {
    const res = await axios<T>({ ...config, method })
    return [res.data as T, null]
  } catch (err) {
    return [null, err as AxiosError<T, T>]
  }
}

Usage

Lets' take a look at how to use it, this example shows using React, you can use another case though.

TSX
import { http } from '@/lib'

import { useEffect, useState } from 'react'

type Product = {
  id: number
  title: string
  price: number
}

export default function App() {
  const [data, setData] = useState<Product | null | boolean>(null)

  useEffect(() => {
    ;(async () => {
      const [res, err] = await http<Product>('GET', { url: 'https://someapi/product/1' })
      if (err !== null) {
        setData(false)
        return
      }
      setData(res)
    })()
  }, [])

  if (data == null) return <p>Loading...</p>

  if (data === false) return <p> whoops, error </p>

  return <p>{data.title}</p>
}

On the above code, specifically inside the useEffect hook, I called an API request to https://someapi/product/1 to get the detail of a product with an id of 1, and then if there's an error, I set the state with false so the UI will shows error. But if nothing goes wrong, I set the state with the data returned from the http() function.

Pretty simple, elegant and beautiful.

Edit on GitHub