"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > A Go-inspired approach to handling fetch API

A Go-inspired approach to handling fetch API

Published on 2024-11-08
Browse:370

A Go-inspired approach to handling fetch API

Javascript error handling can sometimes be confusing especially in using fetch, if you are using await you will need to wrap it in a try catch block to handle the error and we all know that it's a headache

Well what if i tell you we can do something like this

import { get } from "./eavfetch";

interface Book {
  id: string;
  title: string;
  author: string;
}

async function fetchBooks() {
  // data type is inferred as Book[]
  const [data, error] = await get("/books");

  if (error) {
    console.error("Failed to fetch books:", error);
    return;
  }

  if (data) {
    console.log("Fetched books:", data);
  }
}

Now all of the sudden handling fetch seems easy and very straightforward and safe way to handle error and data right? Well that's the power of error as values approach

you can copy the eavfetch.ts/js in the repo and start using it right away.

Release Statement This article is reproduced at: https://dev.to/mmvergara/a-go-inspired-approach-to-handling-fetch-api-3oad?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3