Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

79
Views
How do I refactor this series of API calls to execute faster?

I have a series of API calls I need to make in order to render a grid of image tiles for selection by the user. Right now it takes 3-5 seconds for the page to load and I think it's because I've accidentally added some extra loops, but I'm struggling to discern where the wasted flops are. This is technically a question about NFT data, but the problem is algorithmic not crypto related.

The call sequence is:

  1. Call "Wallet" API to get all assets associated with an address - API doc
  2. On success, call "Asset Metadata" API to get further info about each asset API Doc
  3. Loop step 2 until all assets have a metadata response

This is my code that works (unless there is no assets associated with a wallet), but is just very slow. I'm sure there is a better way to handle this, but I'm struggling to see how. Thanks for your time!

// API Request
var myHeaders = new Headers();
myHeaders.append("X-API-Key", CENTER_API_KEY); //API Key in constants file

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

  const [nftData, updatenftData] = useState();
  const [apiState, updateapiState] = useState("init");
  const [renderNFT, updaterenderNFT] = useState([]);

  useEffect(() => {
    const getData = async () => {
      let resp = await fetch(walletAPICall, requestOptions);
      let json = await resp.json()
      updatenftData(json.items);
      updateapiState("walletSuccess");
    }
    const getRender = async () => {
      let nftTemp = [];
      for (let i=0;i<nftData.length;i++) {
      let tempAddress = nftData[i].address;
      let tempTokenId = nftData[i].tokenId;
      let resp = await fetch(`https://api.center.dev/v1/ethereum-mainnet/${tempAddress}/${tempTokenId}`, requestOptions)
      let json = await resp.json()
      // console.log(json);
      nftTemp.push(json);
      }
      updaterenderNFT(nftTemp);
      updateapiState("NftDataSuccess");

    } 
    if (apiState=="init") {
    getData();
    }
    else if (apiState=="walletSuccess") {
      getRender();
    }
  }, [requestOptions]);
7 months ago · Santiago Gelvez
1 answers
Answer question

0

getRender fetches data items sequentially. You should do it in parallel using Promise.all or Promise.allSettled Something like this...

function fetchItem(item) {
   const res = await fetch(item.url);
   return res.json();
}

await Promise.all[...data.map(fetchItem)]
7 months ago · Santiago Gelvez Report
Answer question
Find remote jobs