Signup/Sign In
LAST UPDATED: FEBRUARY 26, 2024

How to Get Data from Backend in JavaScript? - The Fetch API

    When you are working on a website or a web-based project, you may have to implement a use case where you have to get data from a backend API (service) and display the data on the user interface. To implement this what will you do?

    Will you use some external library like jQuery, to fire in Ajax call to get the data? Or you will look for some native core JavaScript-based solution where you do not have to use any external library. Well, with the Fetch API of JavaScript, you do not have to use any 3rd party library. In just a few lines of code, you can fetch data from backend services and use it in your frontend or user interface.

    JavaScript Fetch API

    Using the fetch() function available in JavaScript you can fire a backend call to get data. When you use the fetch() function, you have to provide the URL of the API as the argument to this function.

    For example,

    let data = fetch("htpps://www.example.com/api/getData")

    Will the fetch function return data?

    No, the fetch() function will not directly return the data, instead, it will return a Promise (in a pending state). What is a Promise? Well, a Promise is an object in JavaScript using which you can track and manage the execution of any async task or operation.

    So, the right way of calling the fetch() function would be,

    let dataPromise = fetch("htpps://www.example.com/api/getData")

    But how do I get the data from Promise?

    By handling the Promise. See, when the fetch() function returns back a promise, it is in a pending state. When the execution of the fetch function is complete, it will update the status of the promise to be fulfilled.

    So you have to specify what you want to do, once the promise gets fulfilled using the then() method or promise object.

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    dataPromise.then((res) => {
        // handle the received response
    })

    The above code can be a little confusing for beginners. So let's break it down a little bit.

    1. We have used the fetch() function to fire an API call, which is an asynchronous call, which means because an API call can take some time (a few milliseconds or seconds), so JavaScript parser will not wait for its completion and will move on to the next line of code to execute it.

    2. In the next line, we have the dataPromise.then() code. Now when the JavaScript parser sees this line of code, it will understand that this has to be executed when the Promise is fulfilled.

    3. Initially, when we execute the fetch() function, it immediately returns back a reference to the Promise object which is stored in the dataPromise variable. This promise object has its state as "pending" right now because the execution of the fetch() function is not yet complete.

    4. Once we get the reference of the Promise in the dataPromise variable, we define the function that must be executed when the Promise is fulfilled or in other words when the fetch() function's execution completes.

    The Promise.then() in Fetch API

    Inside the then() method of the promise, we have to supply a function as a callback, which is executed when the promise is fulfilled.

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    dataPromise.then((res) => {
        // handle the received response
    })

    Expect the response object as a parameter in that function. This response object will bring in the final data from the API call. But you do not get the data directly. To extract the data in JSON format, so that you may directly use it as an object in your JavaScript code, you have to use the json() method of the response object.

    This json() method is also an async method, and it will again return another promise object, in a pending state.

    So, you need to again handle this new promise and specify what should the JavaScript parser do, when this second promise is fulfilled. And how will you do that? Using the then() function.

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    let jsonPromise = dataPromise.then((res) => {
        return res.json()
    })
    
    jsonPromise.then((jsonData) => {
        // handle data
    })

    You can also chain the two then() function calls like this, (you will see code like this more often)

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    dataPromise.then((res) => {
        return res.json()
    })
    .then((jsonData) => {
        // handle data
    })

    Get Data from Fetch API

    Once you have handled the second promise from the json() method call, then you get the JSON data inside it.

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    dataPromise.then((res) => {
        return res.json()
    })
    .then((jsonData) => {
        console.log(jsonData)
    })

    The jsonData in the code above will hold the object with the complete JSON data received from the API call.

    Error Handling in Fetch

    The fetch() function in JavaScript returns a promise, as we discussed above, the promise has several methods that you can use like then() to handle promise fulfillment. Similarly, it has a catch() method that you can use to handle any error that may occur during promise fulfillment.

    Let's see how we can use the catch() method,

    let dataPromise = fetch("htpps://www.example.com/api/getData")
    
    dataPromise.then((res) => {
        return res.json()
    })
    .then((jsonData) => {
        console.log(jsonData)
    })
    .catch((err) => {
        console.error(err);
    })

    In the catch() method, you can do whatever you wish to do with the err.

    Using Async/Await with Fetch API

    To process a Promise, you can either use the then() method on the promise object, or you can use async and await keywords to inform the JavaScript parser to wait for a particular async statement, and watch for Promise getting fulfilled and then continue inside the async function.

    In order to use async and await, we must define all our code inside a function, and mark the function using async keyword, to inform the JavaScript parser that inside that function it may encounter the await keyword, and when it does, it must wait for the Promise to get fulfilled to move on to the next line of code.

    Let's update the code that we have seen up until now,

    async function getData() {
        let dataPromise = await fetch("htpps://www.example.com/api/getData")
        let dataJson = await dataPromise.json();
        console.log(jsonData)
    }

    That's it, see how simple the code looks without all that then() and catch() methods.

    Error Handling with Async/Await

    When you use async and await, then you have to use the usual error handling in JavaScript, using the try and catch setup.

    Let's update the above code to handle the error,

    async function getData() {
        try {
            let dataPromise = await fetch("htpps://www.example.com/api/getData")
            let dataJson = await dataPromise.json();
            console.log(jsonData)
        }
        catch(err) {
            console.log(err)
        }
    }

    The above code is more in line with the simple JavaScript function, it is more readable and clean.

    Conclusion

    Using the Fetch API, you can very easily get data from any API and handle it. The Fetch API is a native API in JavaScript hence you do not have to import any external library or JavaScript file.

    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS