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 l…


This content originally appeared on DEV Community and was authored by mmvergara

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<Book[]>("/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.


This content originally appeared on DEV Community and was authored by mmvergara


Print Share Comment Cite Upload Translate Updates
APA

mmvergara | Sciencx (2024-08-22T23:02:00+00:00) A Go-inspired approach to handling fetch API. Retrieved from https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/

MLA
" » A Go-inspired approach to handling fetch API." mmvergara | Sciencx - Thursday August 22, 2024, https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/
HARVARD
mmvergara | Sciencx Thursday August 22, 2024 » A Go-inspired approach to handling fetch API., viewed ,<https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/>
VANCOUVER
mmvergara | Sciencx - » A Go-inspired approach to handling fetch API. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/
CHICAGO
" » A Go-inspired approach to handling fetch API." mmvergara | Sciencx - Accessed . https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/
IEEE
" » A Go-inspired approach to handling fetch API." mmvergara | Sciencx [Online]. Available: https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/. [Accessed: ]
rf:citation
» A Go-inspired approach to handling fetch API | mmvergara | Sciencx | https://www.scien.cx/2024/08/22/a-go-inspired-approach-to-handling-fetch-api/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.