logoalt Hacker News

reactordevtoday at 3:58 AM2 repliesview on HN

You can do all of that in fetch really easily with the init object.

   fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer ' + accessToken
  }
})

Replies

zdragnartoday at 5:34 AM

There are pretty much two usage patterns that come up all the time:

1- automatically add bearer tokens to requests rather than manually specifying them every single time

2- automatically dispatch some event or function when a 401 response is returned to clear the stale user session and return them to a login page.

There's no reason to repeat this logic in every single place you make an API call.

Likewise, every response I get is JSON. There's no reason to manually unwrap the response into JSON every time.

Finally, there's some nice mocking utilities for axios for unit testing different responses and error codes.

You're either going to copy/paste code everywhere, or you will write your own helper functions and never touch fetch directly. Axios... just works. No need to reinvent anything, and there's a ton of other handy features the GP mentioned as well you may or may not find yourself needing.

show 6 replies
mhiotoday at 4:34 AM

What does an interceptor in the RequestInit look like?

show 1 reply