DEV Community

Cover image for How to use fetch in JavaScript
Samuel Lucas
Samuel Lucas

Posted on

 

How to use fetch in JavaScript

You received a project that you're needed to fetch data from an API and you've got no idea about it, well I'm here to teach you the necessary tricks to get started.

To fetch, wait what's fetch? There are several definitions there but they just aren't simple enough.

Simply, fetch is a way to interact with the database; pass information between frontend and backend.

There are different ways to do this, we have GET, POST, PUT & DELETE. Let's talk a bit about them.

  1. GET: Just as the name implies, it is a way to get data through the API to the frontend.

  2. POST: Well it's still as its name implies. This time you're sending data you created to backend through the API, could be an image or text it any other thing.

  3. PUT: It's very similar to POST just that in the case your updating a data and then sending it back to the backend.

  4. DELETE: Yep, it's just deleting data from the backend via API.

Use case for each.

  1. GET: It receives a single parameter and that's the endpoint you're wanting to fetch data from.
fetch("https://endpoint.com")
Enter fullscreen mode Exit fullscreen mode
  1. POST & PUT: The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings
const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
Enter fullscreen mode Exit fullscreen mode

To know more about this, read up on https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  1. DELETE: The fetch() method can optionally accept a second parameter, an init object that allows you to control the method and headers
fetch('https://example.com/profile', {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json',
  }
})
Enter fullscreen mode Exit fullscreen mode

To know more about this, read up on https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

There you go.

Latest comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!