Search code examples
javascriptes6-promise

Uncaught TypeError: postData(...).then is not a function


I have setup a button that when clicked will post data via fetch and will create an alert. However, I first check to ensure certain inputs are not empty. If the input elements have no value I try to return a string telling me which input element value is empty. When I do, the "Uncaught TypeError: postData(...).then is not a function" error shows up. I have also looked at Uncaught TypeError: $.get(...).then is not a function but could not figure it out. Any help would be greatly appreciated. Thank you!

document.getElementById("sbmForm").onclick = function () {postData(`/projectInfo`)
    .then(result => alert(JSON.stringify(result))) // JSON-string from `response.json()` call
    .catch(error => alert(error))};



function postData(url = ``) {
    // get form data from local storage
    var data = {};
    var unqVal = document.getElementById("unq_num").innerHTML;
    unqVal = "--??**" + unqVal;

    // keys that can not be empty
    var notEmpty = ["comp_name", "compaddr_str_num", "compaddr_str_nam", "compaddr_city",
        "compaddr_state", "compaddr_zipcode", "proj_name", "projaddr_str_num", "projaddr_str_nam",
        "projaddr_city", "projaddr_state", "projaddr_zipcode", "contact_fname", "contact_date"];
    /* get all keys and values from local storage and store them in dict to send to server */
    var keys = Object.keys(localStorage);

    var i;
    for (i=0; i < keys.length; i++){

        var val = localStorage.getItem(keys[i]);

        // if unq val is in string, add it to the data
        var indexOf = keys[i].indexOf(unqVal);

        if (indexOf != -1){

            var keyNU = keys[i].substring(0, indexOf);
            // if value is in array
            if (notEmpty.includes(keyNU)){
                // if value is empty
                if (!val){
                    alert(keyNU + " cannot be empty!");

                    /**** ERROR OCCURS HERE *****/
                    return keyNU + " cannot be empty!";
                }
            }

            data[keys[i]] = val;
        }

    }

    // Default options are marked with *
    return fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
};

Solution

  • You're returning a string value and not a promise when an "error" is detected. The then method only exists on promises.

    Change your function to async so it returns a promise by default.

    async function postData(url = ``){}
    

    Then throw an error when it needs to occur (will be caught by the catch method) by changing this

    /**** ERROR OCCURS HERE *****/
    return keyNU + " cannot be empty!";
    

    To

    throw new Error(keyNU + " cannot be empty!");
    

    Finally, for your fetch:

    //fetch returns a promise, so use await
    const res = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    });
    
    //res.json() returns a promise, so use await
    return await res.json();