I have an array of crypto coin IDs that I need to send in an API call to get data against each coin. How do I iterate it and send in API call?
The IDs array being stored:
const getIds = async () => {
Axios.get(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
).then((response) =>
setCoinIds((coinIds) => [
...coinIds,
...response.data.map((res) => res.id),
])
);
};
The coin details API. The {coin_id}
is where I need to iterate and send api calls against each ID.
export const getCoinsData = async () => {
try {
const response = await Axios.get(
"https://api.coingecko.com/api/v3/coins/${coin_id)"
);
return response.data;
} catch (e) {
console.log(e);
}
};
In the end, I need to store all coin data in a collective object:
const fetchCoinData = async () => {
setLoading(true);
const fetchedCoinData = await getCoinsData();
setData(fetchedCoinData);
setLoading(false);
};
CodePudding user response:
You could iterate the array of IDs while populating an array with the responses from the server.
Also, axios
should be lowercased.
export const getCoinsData = async () => {
let coinsData = [];
for (const id in coinIds) {
try {
const { data } = await axios.get(
'https://api.coingecko.com/api/v3/coins/${id)'
);
coinsData.push(data);
} catch (e) {
console.log(e);
}
}
return coinsData;
};
CodePudding user response:
Using CoinGecko’s API recursively when on a free version is bit tricky. If you go through this API documentation , you will see a statement saying they have rate limit for their API calls.
Our Free API* has a rate limit of 50 calls/minute.
I have rewritten a working code to fetch all coins and get their IDs then recursively call CoinGecko's API for those ids with an interval of 3 sec between each API call, which makes our rate of calling 20 calls/minute.
Here is the code for the same :
Note - You can modify this to fit in with react to set state and all. Currently this can be run with node directly.
import axios from "axios";
const instance = axios.create({
baseURL: "https://api.coingecko.com/api/v3",
});
const delay = async (ms = 3000) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
let coinIds = [];
const getIds = async () => {
try {
const response = await instance.get(
"/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
);
coinIds = [...coinIds, ...response.data.map((coin) => coin.id)];
console.log("