I'm trying to disable import_button
when I click it and enable it when the fetch
is done. I tried to do it like this (code below) but unfortunately, it doesn't work.
Sub question: Can I skip this two lines of code let import_button = document.getElementById('import_button'); import_button.disabled = true;
let import_button = document.getElementById('import_button'); import_button.disabled = true;
and do something like this? this.disabled = true;
<button id="import_button" onclick="fetchProducts(event);">Import</button>
function fetchProducts(e) {
e.preventDefault();
let import_button = document.getElementById('import_button');
import_button.disabled = true;
fetch('/api/v1/products', {
method: 'GET'
})
.then(response => response.json())
.then(products =>
import_result.innerHTML = `Updated: ${products.updated}`
)
.then(import_button.disabled = false)
}
That final then
still needs to be a function
.then(() => import_button.disabled = false)
or just include it in previous then
.then(products => {
import_result.innerHTML = `Updated: ${products.updated}`;
import_button.disabled = false
})
Sub question: sort of. It's the event target
function fetchProducts(e){ let import_button = e.target; console.log(import_button) import_button.disabled = true; }
<button id="import_button" onclick="fetchProducts(event);">Import</button>
So make it let import_button = e.target
You should consider changing the disabled state inside finally
instead of then
so that you can handle the catch
error as well.
You can store button reference using this
:
function fetchProducts(e) {
e.preventDefault();
let import_button = this;
import_button.disabled = true;
fetch('/api/v1/products', {
method: 'GET'
})
.then(response => response.json())
.then(products =>
import_result.innerHTML = `Updated: ${products.updated}`
)
.catch(error => console.log(error))
.finally(() => (import_result.disabled = false))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.