Search code examples
javascriptjqueryfetch-api

How to convert from jQuery to fetch API


I am working on a function

String.prototype.isActualWord = function() {
    if ($ != undefined) {
        let str = this.toLowerCase()
        let res = false
            
            const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";

            try {
                $.ajax({
                    type: "GET",
                    url: url,
                    async: false,
                    success: function (data) {
                        res = true
                    },
                    error: function (data) {
                         res = false
                    }
                })
            }
            catch(e) {
                throw new Error(e.message)
            }
        return res
    } else {
        throw new Error("Please Include jQuery In Your Project")
    }
}

Here is the fetch code:

let res = false
fetch(url)
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    if(data[0] != undefined) {
        res = true
    } 
  });

you see, I want to remove the jQuery dependency from my project. how can I achieve this using the asynchronous way using fetch API. i have tried many ways but in vain.


Solution

  • The fetching of the API is asynchronous so you should wait for it before returning the answer. In the checking you should add async/await too:

    async function testWord(word) {
        let check = await word.isActualWord();
        return check;
    }
    

    And to avoid cors issues add init with cors to the fetch api

    String.prototype.isActualWord = async function() {
      let str = this.toLowerCase()
      let res = false
      let myHeaders = new Headers();
      let myInit = { method: 'GET',
                   headers: myHeaders,
                   mode: 'cors',
                   cache: 'default' };
          
      const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";
    
      try {
        const data = await fetch(url, (myInit as RequestInit))
        .then((response) => {
          return response.json();
        });
          if(data[0] != undefined) {
              res = true
          }
      }
      catch(e) {
        console.log('there was an error', e)
          throw new Error(e.message)
          }
      return res
    }