DEV Community

loading...

Discussion on: Do you prefer Fetch or Axios?

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

axios integrates better with TypeScript interfaces, however, fetch (and well as node-fetch) has much more predictable output.

// Is it `string` or `Record<string, unknown>` (or `Blob`)?
const { data } = await axios.get('/api')

// Nearly always `Record<string, unknown>`
const data2 = await fetch('/api').then((r) => r.json())
Enter fullscreen mode Exit fullscreen mode

Also, fetch can be attached AbortController. I would be interested in a library built on top fetch.

I know there are superagent and ky, but I never really tried.

Collapse
adamazad profile image
Adam Azad

What about?

interface Fruit {
  id: string;
  name: string;
}

const { data } = await axios.get<Fruit[]>('/fruits');
Enter fullscreen mode Exit fullscreen mode

Now data is an array of objects Fruit

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

Actually, it's just a fake typing.

It depends on the "real" data, whether it gets JSON.parse() or not.