javascriptfetch-api

How to get random data from my simple API


I want to make a chrome extension that randomly fetches data from my basic API. I want to get a unique response every time a user clicks. Please help me to do so. Here is my JS code, JSON data sample, and HTML code.

fetch('https://script.google.com/macros/s/AKfycbxOb2CGelDHQDYe7rRABLPRfuqxuFkDwZs4rq1yK0WDs-JEUkFdMftPhUuJjK3WmrOo/exec')
    .then(data2 => data2.json())
    .then(apiData => {
        const displyText = apiData.data[0].name;
        const displayName = document.getElementById('displayName');
        displayName.innerHTML = displyText;
       
    })
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

<link rel="stylesheet" href="style.css">

</head>
<body>

    <p id="displayName">Love You Bihu🧡</p>
    <script src="app.js"></script>

</body>
</html>

{
"data": [
{
"name": "Akash"
},
{
"name": "Bihu"
},
{
"name": "Tuhin"
},
{
"name": "Nilu"
},
{
"name": "Akash"
}
]
}


Solution

  • you just add random function then get random numbers.

    const random = (min, max) => Math.floor(Math.random() * (max - min) + min);
    
    fetch(
      "https://script.google.com/macros/s/AKfycbxOb2CGelDHQDYe7rRABLPRfuqxuFkDwZs4rq1yK0WDs-JEUkFdMftPhUuJjK3WmrOo/exec"
    )
      .then((data2) => data2.json())
      .then((apiData) => {
        const displyText = apiData.data[random(0, apiData.data.length)].name;
        const displayName = document.getElementById("displayName");
        displayName.innerHTML = displyText;
      });