DOM EVENT API JavaScript
DOM EVENT API JavaScript
Which event triggers in DOM when data is fetched from an api? I want to add event listener (javascript) to manipulate DOM when data is fetched from api. I have tried onload,onchange events these are not working.
4 Answers
4
There are lots of different APIs which can be used to fetch data.
I'm not aware of any of them which trigger an event in the DOM.
Many of them have their own (non-DOM) events. For example, XMLHttpRequest
instances have a load event.
XMLHttpRequest
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
I suggest to work a bit on javascript fetch and promises:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
you can "fetch" any resource from web, and do something when data (json from an api, image, any resources...) is fetched using promises
There's no event for requests. You can add a service worker which has it or you can just call a function from the 'load' event of all XMLHttpRequest objects or the .then() method if you are using fetch() API.
If you are trying to cacth the event of fetched data when the DOM element is affected by the data you can try to use Mutation Observers (depending on the change in the dom you are waiting for):
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Ib you try to cactch the event just to check the feched data the method Quentin mentioned above
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.