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);
});
}