Search code examples
javascripthtmlapies6-promisefetch-api

Without clicking the button to fetch data in js, my page fetched data automatically, and there is the second call to button


Can anyone help me with that- I am using fetch api here and this is linked to a button ,here I used fetch api for a get request, but the problem is that without clicking the button ,my data is fetched from the api. When I clicked the button to fetch data first time, it works perfectly but after that on reload my data is fetched automatically without clicking button. what's the problem here and how to fix it?

easyhttp.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>easy http</title>
</head>
<body>
    <ol id="getRequestData">
        
    </ol>
    <button id="btn1">get</button>
    <button id="btn2">post</button>
    <button id="btn3">put</button>
    <button id="btn4">delete</button>
    <script src="easyHttpWithFetch.js"></script>
</body>
</html>

easyHttpWithFetch.js

document.getElementById("btn1").addEventListener("click",get("https://jsonplaceholder.typicode.com/posts"));
function get(url){
    fetch(url)
        .then(response => response.json())
        .then((data) => {
            let str = "";
            data.forEach(element => {
                str += '<li><ol type="a">';
                for (const key in element) {
                    if (Object.hasOwnProperty.call(element, key)) {
                        const value = element[key];
                        str+= `<li>${value}</li>`;
                    }
                }
                str += '</ol></li>';
                let getRequestData = document.getElementById("getRequestData");
                getRequestData.innerHTML = str;
            });
    }).catch((err) => {
        console.log(err);
    });
}

Solution

  • The second parameter of the addEventListener() is the function name that we want to call when the click occurs. But you are currently trying to execute the get() method by passing the url parameter immediately. That's why get() is first called initially when btn1 is attached to the click event.

    To fix this, try to use the arrow function.

    document.getElementById("btn1").addEventListener("click",  () => get("https://jsonplaceholder.typicode.com/posts"));
    
    function get(url) {
      fetch(url)
        .then(response => response.json())
        .then((data) => {
          let str = "";
          data.forEach(element => {
            str += '<li><ol type="a">';
            for (const key in element) {
              if (Object.hasOwnProperty.call(element, key)) {
                const value = element[key];
                str += `<li>${value}</li>`;
              }
            }
            str += '</ol></li>';
            let getRequestData = document.getElementById("getRequestData");
            getRequestData.innerHTML = str;
          });
        }).catch((err) => {
          console.log(err);
        });
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>easy http</title>
    </head>
    
    <body>
      <ol id="getRequestData">
    
      </ol>
      <button id="btn1">get</button>
      <button id="btn2">post</button>
      <button id="btn3">put</button>
      <button id="btn4">delete</button>
    </body>
    
    </html>