Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    A tiny ES6 fetch() wrapper that makes your life easier

    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.

    Published on November 2nd, 2016 in Front End, react, Technical

    Did you enjoy this article?

    Continue reading about A tiny ES6 fetch() wrapper that makes your life easier

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️