Awonke Mnotoza

Site Owner

Data Fetching with JavaScript

26 May 2023

0
share

What is Data?

Data refers to the information collected, stored, and used for different purposes.

It can be in any form of presentation, such as images, texts, videos, etc.

Data can be structured or unstructured and it can be processed and analyzed to gain insights to make informed decisions.

In this modern world that we live in now, data is vital.

Almost every application on the web uses data because users need data.

As a developer, you must know how to collect, read, and present data.

What is data fetching?

To make it simple as it sounds, data fetching is the process of fetching data.

As a developer, you will be fetching data from an API (Application Programming Interface).

Whether you are creating a simple project or a complex project, efficient data fetching is crucial for a seamless user experience.

JavaScript, being the language of the web, offers various methods and techniques for fetching data from APIs, databases, and other sources.

Below I will cover these methods and provide understandable explanations to help you understand better.

Using the fetch API - Chaining

The Fetch API is a modern and powerful feature in JavaScript that simplifies the process of making network requests.

As a developer, you will mostly use this method.

It returns a Promise, allowing us to handle the response asynchronously.

Asynchronous fetching allows the program to continue executing other tasks while waiting for the data to be retrieved, without blocking or freezing the user interface.

Let us look at a practical example:

Contawo: javascript

Copy

fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
            // Process the fetched data
            console.log(data);
      })
      .catch(error => {
            // Handle any errors
            console.error('Error:', error);
      });

Now let us break the code down.

The fetch gets the data from the API that we have provided, then returns a Promise, which contains a resolve (data fetched successfully) or a reject (data not fetched successfully).

The resolve is handled by the then method. that helps us to get the data.

We convert that data into JSON (JavaScript Object Notation) which will enable us to read and use the data effectively.

The reject is handled by the catch, where we catch the errors if the data was not fetched successfully.

Remember to always handle errors when fetching your data, because sometimes you might not get the data, due to network problems, server problems, etc

Using the Fetch API - Async

This method is the same as the one above, but here we are going to implement the async await.

Let us see some practical examples:

Contawo: javascript

Copy

async function fetchData() {
      try {
            const response = await fetch('https://api.example.com/data');
            if (!response.ok) {
                  throw new Error('Network response was not ok');
            }
            const data = await response.json();
            // Process the fetched data
            console.log(data);
      } catch (error) {
            // Handle any errors
            console.error('Error:', error);
      }
}

fetchData();

Let me break this down.

We start by creating an asynchronous function that will enable us to fetch the data asynchronously.

The try is used to get the data if it exists and the catch is meant to get an error, if the data does not exist.

Inside the try block, we are going to wait for the data to be fetched, then we check if the response is ok (meaning the data has been fetched successfully).

If not we throw an exception, that will take us to the catch block.

If we get ok status, we then convert the data into JSON format, then later use the data.

You might need some fresh air before you read the below.

XMLHttpRequest (XHR) method

This is a JavaScript API that is used to create AJAX requests.

AJAX enables us to work asynchronously, meaning that our program will continue running while we are fetching the data.

While the Fetch API is recommended for new projects, understanding XHR can be helpful when working with legacy codebases.

Here is an example:

Contawo: javascript

Copy

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 400) {
            const data = JSON.parse(xhr.responseText);
            // Process the fetched data
            console.log(data);
      } else {
            // Handle the HTTP error
            console.error('HTTP Error:', xhr.status);
      }
};

xhr.onerror = function() {
      // Handle any network errors
      console.error('Network Error');
};

xhr.send();

We created the XMLHttpRequest instance so that we can take advantage of the features it has.

Then we opened a method to get our data, using the get method, followed by the API key and then a boolean (to specify whether we are going to use asynchronous).

After we have opened, we need to get the data by loading it.

In the loading, we check whether we have received the data and handle the error if we get a status that is not 200 (commonly 400)

Then we also want to check for any network errors.

Lastly, we send the data so that we can see it.

Using third-party Libraries

JavaScript offers various third-party libraries that simplify data fetching and provide additional features.

One example of these libraries is Axios.

Let us see an example:

Contawo: javascript

Copy

axios.get('https://api.example.com/data')
      .then(response => {
            const data = response.data;
            // Process the fetched data
            console.log(data);
      })
      .catch(error => {
            // Handle any errors
           console.error('Error:', error);
      });

What I like about this Library is that we get our data from the data method.

Another benefit of using this library is that it provides features like request cancellation and automatic JSON parsing.

Learn more about JavaScript and the Web

If you are curious like me and want to learn more about JavaScript and the Web.

Also get a certificate of completion, so that you can start applying for jobs.

Start learning today by clicking the link below.

Please comment on your thoughts and any questions you have.

Comments

Be the first to comment...