Reputation: 1367
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>
Upvotes: 0
Views: 123
Reputation: 350202
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));
}
Upvotes: 1
Reputation: 5084
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>
Upvotes: 0
Reputation: 11209
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.
Upvotes: 0