const BASE_URL = https://api.worldbank.org/v2/country/; // Define the API URLs,…
- User
const BASE_URL =
https://api.worldbank.org/v2/country/; // Define the API URLs, indicators, and countries const apiUrlsAndIndicators = [ { endpoint: 'NY.GDP.MKTP.CD', indicator: 'GDP (current US$)' }, { endpoint: 'FR.INR.RINR', indicator: 'Interest Rate' }, { endpoint: 'FP.CPI.TOTL.ZG', indicator: 'Inflation Rate' }, { endpoint: 'SL.UEM.TOTL.NE.ZS', indicator: 'Unemployment Rate' }, { endpoint: 'NE.EXP.GNFS.CD', indicator: 'Trade Balance' }, /* { endpoint: 'GC.XPN.TOTL.GD.ZS', indicator: 'Government Spending' } */ ];//&date=2021
export async function fetchData(indicator, countryCode) { const { endpoint } = apiUrlsAndIndicators.find(i => i.indicator === indicator); const url =
${BASE_URL}${countryCode}/indicator/${endpoint}?format=json;try { const response = await fetch(url); const data = await response.json(); console.log(data); let indicatorData = data[1][0]; let i = 0; while (indicatorData.value === null && i < data[1].length) { i++; indicatorData = data[1][i]; } if (indicatorData === null) { return indicatorData; throw new Error('All values in data array are null'); } return indicatorData; } catch (error) { /* console.error(error); */ return null; } } How to prevent more than one call because it's getting called too many times
- Assistant
To prevent the fetchData function from being called too many times, you can add a memoization technique to cache the results of the API call. Here's an example of how to implement it with a simple JavaScript object used as a cache:
const CACHE = {}; export async function fetchData(indicator, countryCode) { const { endpoint } = apiUrlsAndIndicators.find(i => i.indicator === indicator); const cacheKey = `${countryCode}_${endpoint}`; // If the data is cached, return it directly if (CACHE[cacheKey]) { return CACHE[cacheKey]; } const url = `${BASE_URL}${countryCode}/indicator/${endpoint}?format=json`; try { const response = await fetch(url); const data = await response.json(); console.log(data); let indicatorData = data[1][0]; let i = 0; while (indicatorData.value === null && i < data[1].length) { i++; indicatorData = data[1][i]; } if (indicatorData === null) { return indicatorData; throw new Error('All values in data array are null'); } // Cache the result before returning it CACHE[cacheKey] = indicatorData; return indicatorData; } catch (error) { /* console.error(error); */ return null; } }By using the
CACHEobject, the function will store the results of the API calls and return them directly instead of making a new API call when the function is called with the sameindicatorandcountryCodeas before.Keep in mind that the cache will persist only as long as the script is running. If you need a more advanced or long-term caching mechanism, you can consider using something like IndexedDB or the Cache API in the browser.