DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

A Tiny ES6 fetch() Wrapper That Makes Your Life Easier

In this post we take a look at a small wrapper for ES6 fetch() that could make your life easier. Read on to find out more!

Swizec Teller user avatar by
Swizec Teller
·
Nov. 04, 16 · Tutorial
Like (1)
Save
Tweet
Share
5.27K Views

Join the DZone community and get the full member experience.

Join For Free

After yesterday's shenanigans with ES6 fetch(), I made a tiny library called better-fetch which makes your life easier. Or at least it makes my life easier.

Without changing the API, better-fetch automatically includes cookies, which would have saved me a very frustrating amount of time yesterday, lets you add default headers, and you can pass request body as a plain JS object. None of that FormData nonsense.

better-fetch works the same as fetch(), but is less cumbersome to use.

In Practice, Better-fetch Looks Like This:

You install with npm. Or whatever you use to install packages from npmjs.org. Yarn maybe?

$ npm install --save better-fetch

Then you set up headers that every one of your fetch() calls needs. My backend requires an Authorization and an Accept header from all calls.

// top of project
// src/index.js

import fetch from 'better-fetch';

fetch.setDefaultHeaders({
    Authorization: `Token token=${GlobalTokenValue}`,
    Accept: "application/json.v2"
});

// ^ this is optional and depends on your use-case ^

You can then use better-fetch anywhere in your code as you normally would with fetch(). The API feels the same and promises to work just like you'd expect.

// any file
import fetch from 'better-fetch';

fetch('/api/some/thing')
  .then(response => response.json())
    .then(json => {
        // do stuff
    });

This code fetches JSON document with a GET request to the /api/some/thing URL. Any default headers are set in the request and cookies are sent as well.

POST-ing is also made less cumbersome:

// any file
import fetch from 'better-fetch';

const data = {
    key: 'value',
    key2: 'value2'
};

fetch('/api/save_response', {method: 'POST',
                             body: data})
          .then(response => response.json())
          .then(json => {
              console.log(json);
          });

A dictionary body is automatically transformed into a FormData object, and strings and FormData objects are let through. This gives you flexibility to work with any API backend, but it still makes your life easier.

Similarly, you can specify headers as either a Headers object or a dictionary – better-fetch has you covered.

Happy hacking

PS: I know a bunch of fetch wrappers exist already. They all make significant changes to the API, and I wanted to avoid that.

Fetch (FTP client)

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • OpenID Connect Flows
  • Understanding gRPC Concepts, Use Cases, and Best Practices
  • Web Application Architecture: The Latest Guide
  • Using the PostgreSQL Pager With MariaDB Xpand

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: