DEV Community

Cover image for Attempt to simplify the fetch API
Jaden Concord
Jaden Concord

Posted on

Attempt to simplify the fetch API

The fetch API is awesome and super easy to use but I made an attempt to simplify fetch for my needs. I like to take API's or functions and simplify them as much as I can for my needs. Here was what I wanted to simplify about the fetch API.

  1. One function for success and one function for all errors
  2. Automatic JSON or text parse
  3. Easily send body and easily change header data

Lets start with a fetch example with promises to try to simplify:

fetch('https://example.com')
.then(x => x.text())
.then(y => alert(y))
.catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

Now this is what I want to be able to do:

fetcher('https://example.com')(alert)(console.error)
Enter fullscreen mode Exit fullscreen mode

It looks odd but all its just a function that returns a function that returns a function that does what we want. Its called fetcher because fetcher is not fetch. Here is the code we could use to fulfill the above.

function fetcher(url, options){
  options = {
    parse: 'text',
    ...options
  }

  return (done) => {
    return (error) => {
      try{
        fetch(url).then(x => x[options.parse]()).then(done).catch(error);
      } catch(err) {
        error(err);
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This is just the start to this idea. I will later add things like request body and headers to the options but this is it for now as a start.

Top comments (3)

Collapse
 
kidkkr profile image
kidkkr

I think the code before is a bit more explicit and easier to understand.

Collapse
 
jadenconcord profile image
Jaden Concord

The original code is definitely easier to understand and read I agree but I was just trying to see if I could simplify it for personal projects on one line.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.