axios vs. fetch api
I saw a lot of examples are using fetch api, and wonder if this can completely replace axios? What are pros and cons for each? I'd like to have one less library to maintain, so I'd like to know if axios has something fetch api can't do. Thanks!
8 Replies
dependent-tan•3y ago
Tanstack query can totally be used with
fetch instead of axios ! The main difference is that by default axios throws an exception when the response http status is not 200 (not "success") whereas fetch doesn't.
Tanstack query needs the query function to throw an exception in order to report the query status as "error" and to call callbacks like onError. So when using fetch you have to check for the response status and throw an exception if it's not successful.
Here is an example: https://tanstack.com/query/v4/docs/react/guides/query-functions#usage-with-fetch-and-other-clients-that-do-not-throw-by-defaultQuery Functions | TanStack Query Docs
A query function can be literally any function that returns a promise. The promise that is returned should either resolve the data or throw an error.
All of the following are valid query function configurations:
rival-blackOP•3y ago
Interesting... I took axios for granted. It seems it's not a big hassle to replace it though, just a few more lines.
dependent-tan•3y ago
Exactly!
foreign-sapphire•3y ago
TanStack Query is query function implementation agnostic. As long as you return a promise, you're fine 🙂
correct-apricot•3y ago
alright so sounds good but how exactly would i access the status code of the query from react query
foreign-sapphire•3y ago
If you're interested in the response status code then you'd need to include this in the return from the query function
correct-apricot•3y ago
so basically just return the status code along with the data
foreign-sapphire•3y ago
Yeah