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.
- One function for success and one function for all errors
- Automatic JSON or text parse
- 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));
Now this is what I want to be able to do:
fetcher('https://example.com')(alert)(console.error)
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);
}
}
}
}
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)
I think the code before is a bit more explicit and easier to understand.
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.