0

I have a fetch API that fetches a response from the backend and I have a function inside the fetch that alerts the response. What I am trying to do is run the function on click of a button but the test function is not on the global scope so my button can't access it to run it. Is there any way I can run the function to alert the response on button click after getting the response? Any help is appreciated. Thanks in advance.

fetch(`http://localhost:PORT/api/ROUTE`)
  .then(res => res.json())
  .then((response) => {

    function test() {
      alert(response)
    }
  })
<button onclick="test()">CLICK ME</button>

1
  • try to use javascript promise Commented Jun 4, 2021 at 5:54

3 Answers 3

1

Note that in your current code, test is not even called by the then callback. Move that function into the global scope, but be aware that anyway if you click too soon, the response might not be available yet. So work with the promise:

let promise = fetch(`http://localhost:PORT/api/ROUTE`)
              .then(res => res.json());
test(); // Optional -- if you want to have the alert even when button is not clicked.

function test() {
   promise.then(response => alert(response));
}

If your purpose was to redo the fetch on every button click, then move all that logic inside test.

test(); // Optional -- when you want to initiate the fetch on page load

function test() {
   fetch(`http://localhost:PORT/api/ROUTE`)
       .then(res => res.json());
       .then(response => alert(response));
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to show the alert after fetch completion:

function getdata() {
    fetch(`http://localhost:PORT/api/ROUTE`)
      .then(res => res.json())
      .then((response) => {

        function test() {
          alert(response)
        }
      })
}

<button onclick="getdata()">CLICK ME</button>

getdata is called and fetch initiated. Upon fetch completion, test is called. Note that you can do multiple clicks and have fetches running in parallel.

Comments

0

You need to declare a variable in global scope, and assign a function to it upon fetching the data.

var test;

fetch(`https://api.github.com/users/techysharnav/repos`)  //For Test purposes
  .then(res => res.json())
  .then((response) => {
     test = (response)=>alert(response)
  })
<button onclick="test()">CLICK ME</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.