Science Knowings: JavaScript Course For Social Media

Fetch API

Previously on Promises...

In our previous session, we explored Promises, a powerful tool for handling asynchronous operations. Promises allow us to write asynchronous code in a more structured and predictable way.

Introducing Fetch API

Fetch API: A Modern Approach to Fetching Resources

The Fetch API provides a standardized and simplified way to fetch resources from the server. It's a powerful tool for building modern web applications.

Benefits of Fetch API

  • Easy to use and consistent syntax
  • Support for modern browsers
  • Promise-based, making it easy to handle asynchronous requests
  • Powerful features like request and response headers

Making a Fetch Request

fetch(url, options)

Where url is the resource to fetch and options is an optional object to configure the request.

Syntax of Fetch Request

fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Response Handling with Fetch API

The fetch request returns a Promise that resolves to a Response object. We can then handle the response using .then() and .catch() for successful and error scenarios respectively.

Response Status Codes

CodeDescription
200OK
404Not Found
500Internal Server Error

Handling Fetch Errors

Errors can occur during a fetch request. We can handle them using .catch() and display meaningful error messages to the user.

Consuming JSON Data with Fetch

fetch(url)
.then(response => response.json())
.then(data => console.log(data))

This allows us to easily parse JSON data returned from the server.

Posting Data with Fetch

fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})

This allows us to send data to the server using the POST method.

PUT and PATCH Requests with Fetch

Similar to POST, we can use PUT and PATCH methods to update and partially update resources respectively.

Custom Error Handling with Fetch

We can create custom error messages by throwing errors within .catch().

Practical Examples of Fetch API

  • Loading external data
  • Making API calls
  • AJAX requests

AJAX with Fetch API

Fetch API can be used to perform AJAX requests, allowing for asynchronous communication with the server.

Next Topic: Async/Await

In the next session, we'll dive into Async/Await, a powerful tool for making asynchronous code more readable and manageable. Follow us to learn more!