Home > Back-end >  Disable button while waiting on async function to finish
Disable button while waiting on async function to finish

Time:09-17

I am looking for a way to disable my "fetch data" button until the data has been fetched. currently i have this code:

const FetchButton = document.getElementById("fetch");
const itemDiv = document.getElementById("item-div");

const fetchData = async () => {
  const randomPokemonId = Math.floor(Math.random() * (1   898 - 1));
  const URL = `https://pokeapi.co/api/v2/pokemon/${randomPokemonId}`;
  console.log(randomPokemonId);
  try {
    let res = await fetch(URL);
    res = await res.json();
    itemDiv.innerHTML = res.name;
    return res;
  } catch (err) {
    console.log(err);
  }
};

FetchButton.addEventListener("click", fetchData);

How can i do this the best way?

Thank you in advance!

CodePudding user response:

fetchData is already an async function, so should return a promise. Rather than call this directly, wrap it in a function that calls it and adds a then to it:

const fetchButtonClick = () => {
    FetchButton.disabled = true
    fetchData().then(
        () => FetchButton.disabled = false
    )
}

CodePudding user response:

With a wrapper.

    const FetchButton = document.getElementById("fetch");
    const itemDiv = document.getElementById("item-div");
    
    const getPokemon = async () => {
          FetchButton.disabled = true;
          const pokemon = await fetchData();
      
          if(!!pokemon){
              itemDiv.innerHTML = pokemon.name;
          }
        FetchButton.disabled = false;
    }
    
    const fetchData = async () => {
      const randomPokemonId = Math.floor(Math.random() * (1   898 - 1));
      const URL = `https://pokeapi.co/api/v2/pokemon/${randomPokemonId}`;
      console.log(randomPokemonId);
      try {
        let res = await fetch(URL);
        res = await res.json();
        return res;
      } catch (err) {
        console.log(err);
      }
    };
    
    FetchButton.addEventListener("click", getPokemon);

Pen here: https://codepen.io/freedruk/pen/powNbXL

  • Related