Data Fetching In Javascript

Data Fetching In Javascript

Understand how to fetch data using the fetch API

·

4 min read

OVERVIEW

One of the easiest way to fetch data in javascript is by using the fetch API which enables developers to send Http requests to a database using promise.

A promise is an object representation of the eventual completion or failure of an asynchronous operation.

Mr A promises Mr B a plot of land by the end of the week, while Mr B is waiting for Mr A to fulfil his promise, the promise is in a state called PENDING, if at the end of the week, Mr A fulfil his promise, the promise is in a state called FUFILLED, and if Mr A defaults and doesn't fulfil his promise, the promise assumes the REJECT state.

In a lame man's language, every organization have a database where data is stored, for instance, when you visit the hospital for treatment, one of these actions are carried out;

CREATE: Creating a new file if you are a new patient synonymous to when you create a new account on a platform,

READ: When the doctor or nurses go through your file/folder, synonymous to when someone visits your profile,

UPDATE: After consultation, the doctor discovered a new diagnosis/ the nurse updated your vital signs, synonymous to when you update your profile on a platform,

DELETE: I doubt if this kind of operation happens in a hospital, but it is synonymous to when you delete your account from a platform.

The database here is the records department, but in the tech world, a database is a place where organization data are stored, a very good example of such platform is mongodb, firebase.

To fetch data from a database, you need an API (Application Programming Interface).

An API is a set of programming codes that allows data transmission from one software or device to another.

When you open your Facebook account change your profile picture, an API allows you to send a request to update your profile picture on facebook's database, in short an API allows you to communicate with a database.

HOW DO YOU USE AN API TO FETCH DATA?

In this tutorial, I will use a firebase dummy backend API to fetch data from firebase database;

fetch('https://tutorial-e690b-default-rtdb.firebaseio.com/tutorial.json')

Sending this fetch request to the firebase database returns a promise, don't forget, I talked about promises above, at this point the promise is pending, because it hasn't been resolved/fulfilled neither has it been rejected.

So next step is to consume this promise, and I can either do this by using async/await method or by using the then method.

I will be using the then method here;

fetch('https://tutorial-e690b-default-rtdb.firebaseio.com/tutorial.json')
.then(response => response.json())

using the then method on this promise returns a response, it is from the response that we will know if the promise was fulfilled or rejected

if you log the response to the console, you will get an object with some parameters like status, ok, headers, body.

The response is then converted to JSON, which is a text based format for representing structured data in javascript.

If the promise was rejected, the ok property will be false, and it will throw an error, so we can use this to handle the error,

fetch('https://tutorial-e690b-default-rtdb.firebaseio.com/tutorial.json')
.then(response => {
return response.json
if (!response.ok) {
throw new Error('Your request failed, try again')
})

So if the promise was rejected, it will be caught and the error will be thown by using the throw error method,

The response returns another promise that can be resolved by calling another then method on the promise, this then method returns the fetched data from the database in JSON(javascript object notation) format,

fetch('https://tutorial-e690b-default-rtdb.firebaseio.com/tutorial.json').then(response => {
return response.json
if (!response.ok) {
throw new Error('Your request failed, try again')
}).then(data => {
console.log(data)
})

The returned data, mostly in an array is then utilized.

In case there is an error, the catch method can be used to handle the error;

fetch('https://tutorial-e690b-default-rtdb.firebaseio.com/tutorial.json').then(response => {
return response.json
if (!response.ok) {
throw new Error('Your request failed, try again')
}).then(data => {
console.log(data)
}).catch(error) {
console.error(error.message)
}

The catch method returns an error object containing the error message we threw at the top, the developer can then display the error to the interface accordingly to alert users about what went wrong with their requests.

This tutorial only covers one of the data fetching method, which is the GET method, i think it's the simplest, we have others like POST, DELETE, PUT.

I hope you learnt something new?

Don't forget to follow me for more!!

#candie