garyprinting.com

Mastering JavaScript Basics: Day 32 - PUT Requests with Fetch API

Written on

Chapter 1: Introduction to Fetch API

Welcome to Day 32 of our 100-day journey into mastering JavaScript! Today, we’ll dive into making PUT requests using the Fetch API, an essential skill for any aspiring developer.

This adventure of 100 days focused on learning, practicing, and growing is incredibly fulfilling. Let's explore how to make a PUT request with the Fetch API in JavaScript.

Video Description: A comprehensive tutorial on JavaScript, covering everything from beginner to advanced topics to enhance your skills.

How to Execute a PUT Request

Assuming we want to update data on an external API using the PUT method, we'll use the JsonPlaceholder website, a free and reliable API for testing and prototyping.

Getting Started

Note: The PUT method is typically employed for updating records.

Basic Syntax of Fetch API with Options

#### Step 1: Initiate Fetch with the Endpoint

The first step is to call the fetch() function with the endpoint URL.

fetch(url);

#### Step 2: Define URL and Options

Next, you will define the data to be sent and the options for your fetch request, including the method, headers, and body.

Here's the code for the data we need to send:

const putData = {

id: 1,

title: 'footest',

body: 'barddd',

userId: 1,

};

const options = {

method: 'PUT',

headers: {

'Content-Type': 'application/json', // Setting the content type to JSON

},

body: JSON.stringify(putData), // Converting the data to a JSON string

};

#### Step 3: Complete the Fetch Request with Options

Integrate the options into the fetch request:

fetch(url, options)

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok');

}

return response.json(); // Parsing the JSON response

});

#### Step 4: Handle the Promise

To manage the promise, add a .then() statement. Here’s the complete code with promise handling:

fetch(url, options)

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok');

}

return response.json(); // Parsing the JSON response

})

.then(data => {

console.log('Data updated successfully:', data);

});

#### Step 5: Manage Exceptions with Catch

To handle errors during the fetch request, use a .catch() statement:

fetch(url, options)

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok');

}

return response.json(); // Parsing the JSON response

})

.then(data => {

console.log('Data updated successfully:', data);

})

.catch(error => {

console.error('There was a problem with the fetch operation:', error);

});

Step 6: Testing the Code

You can run the above code in any JavaScript application on your local machine or use an online JavaScript playground.

Step 7: Final Debugging in the Network Tab

Open Developer Tools and click on the Network tab. You will see the request with all parameters and options. For the PUT method, you should observe the request payload and a status code of 200 OK when the resource is updated successfully.

Chapter 2: Conclusion

The above code serves as a basic example; remember to replace 'url' with the actual URL you want to send the PUT request to, and adjust the putData object to fit your specific needs.

Stay tuned for tomorrow's lesson, where we'll explore the Fetch API with DELETE method examples.

Thank you for joining me today on this JavaScript journey with Kirti Kaushal. Happy coding!

Video Description: A complete course on JavaScript for beginners to advanced users, covering everything you need to know in just 6 hours.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Title: Embracing Life Choices Without Apology or Guilt

Discover the freedom of living life on your own terms without societal expectations or guilt.

Overcoming Self-Care Barriers: Myths and Realities

Explore common myths that hinder self-care and discover effective strategies for overcoming them.

Inspiration from Josh Wardle: The Visionary Behind Wordle

Discover how Josh Wardle's journey led to the creation of Wordle, a game that unites millions through its simple yet engaging format.

Innovative Solutions for Complex SQL Challenges in Tech Startups

Exploring the common pitfalls in SQL problem-solving and introducing an innovative approach for startups to overcome database challenges.

A Fresh Perspective on the 40-Hour Workweek Struggle

Exploring the challenges of the 40-hour workweek and seeking fulfillment in a demanding world.

The Imperative of Data Ownership as a Fundamental Human Right

Advocating for personal data ownership as a human right is essential in today's digital landscape, where data is increasingly valuable.

Why SpaceX Front End Engineers Have a Unique Challenge

A light-hearted comparison of front-end development at SpaceX versus Google Meet, highlighting unique challenges and user expectations.

Finding Peace with Mortality: Transforming Fear into Freedom

Discover three transformative steps to confront and embrace the fear of death, leading to a more fulfilling life.