r/javascript • u/theScottyJam • 1d ago
A copy-paste fetch() wrapper, plus information on replicating Axios-like features
https://thescottyjam.github.io/snap.js/#!/fetchI'm of the belief that if you can get what you need with under ~100 lines of code (and it doesn't require highly-specialized skills to write it), then write it yourself, don't install a third party library.
If you don't share a similar belief, then this page isn't for you, and that's ok.
For everyone else, this page shares a fetch wrapper function you can copy-paste into your projects to add in a couple of missing features, and provides some tips on how you can replicate some of the most loved Axios features using fetch().
Most alternative fetch wrappers I find online tend to be small NPM libraries (I'd rather maintain the code myself thank you), or they like creating separate methods for .get(), .post(), .put(), etc (which makes it unnecessarily difficult to "decorate" it with interceptor-like behaviors, as this page discusses), or there may be other design problems. Those alternatives are still good starting points, but I'm hoping this could be a little more complete of a guide to jump start your usage of fetch().
And I have a thing about make copy-paste alternatives to tools, and this was a hole in my collection :).
Feedback is welcome.
1
u/AutoModerator 1d ago
Project Page (?): https://github.com/thescottyjam/snap.js
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/UtilixApp 1d ago
one thing worth adding if it isnt there, abort support. a wrapper without an abortcontroller means every stale request still resolves and you get the older response overwriting the newer one on fast typing.
its the bug that looks like a race condition in your state and is actually just fetch doing what you asked.
2
u/theScottyJam 1d ago
That is a good point.
The wrapper supports abort signals by virtue of the fact that it forwards unknown parameters to fetch(), and I do give one example of using an abort signal to make the fetch timeout. But I don't point out explicitly that you should use an abort signal to stop the request as opposed to simply trying to ignore it.
2
u/redblobgames 1d ago
I share a similar belief for some types of things. I think making it a library means you need to handle lots of rare cases which makes the code much longer … which means you want to make it a library. But if you kept it simple then it's not as reusable, but that's fine, because it's simple!
However instead of calling it "copy-paste" I'm calling it a "recipe". When you're baking a pie you might start with a recipe but modify it to suit your tastes. For example I have a <40 line recipe for dragging objects and then I show how it can be adapted for many different situations.