I'm grabbing json data using fetch
and rendering list items with the results. The function containing fetch
is triggered by a button. However, if I click it while the initial fetch
is still going, data from it will be loaded on top of my new call.
I've used window.stop()
to halt this behaviour but is there a better solution?
function updateTable() {
fetch('/json')
.then((response) => {return response.json()})
.then((response) => {
response.records.forEach(el => {
return '<li>' + el.Name + '</li>';
})
})
}
$('button').click(function(){
window.stop();
$('body').empty();
updateTable()
})
Edited with answer: Upon re-reading the linked thread on using the new signal
property with fetch
, I updated my code to work with the new AbortController
. The trick, documented here, is to re-define the controller whenever the function is called again. The advantage vs. window.stop()
is that stoppage only affects this fetch
.
var controller = "";
var signal = "";
function updateTable() {
controller = new AbortController();
signal = controller.signal;
fetch('/json', {signal})
.then((response) => {return response.json()})
.then((response) => {
response.records.forEach(el => {
return '<li>' + el.Name + '</li>';
})
})
}
$('button').click(function(){
controller.abort();
$('body').empty();
updateTable()
})