Uncaught TypeError: response.json is not a function at HTMLButtonElement

Viewed 575

I am stuck with this I am new to web development, any help would be highly appreciated. Can't figure out what's wrong in my code, I get an error Uncaught TypeError: response.json is not a function

const getButton = document.querySelector('.get')
function getData(){
  const response = fetch("https://reqres.in/api/users");
  const data = response.json();
  console.log(data)
}
 getButton.addEventListener('click',getData)
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <button class="get">GET</button>
    </div>
    <script src="sandbox.js"></script>
</body>
</html>

2 Answers

Using async/await

const getButton = document.querySelector('.get')

async function getData() {
  const response = await fetch("https://reqres.in/api/users");
  const data = await response.json();
  console.log(data)
}

getButton.addEventListener('click', getData)
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <button class="get">GET</button>
  </div>
  <script src="sandbox.js"></script>
</body>

</html>

As mentioned, fetch() is asynchronous. Try this:

const getButton = document.querySelector('.get')
function getData(){
    const response = fetch("https://reqres.in/api/users")
        .then(function(data) {
            // This will run on on response from the server
            // AAA
            console.log(data);
        })
        .catch(function(error) {
            // Deal with errors here
        });
    // BBB
}
getButton.addEventListener('click',getData);

so code at BBB will probably run before the code at AAA

Related