I have an array of objects stored in a currentCoins state as follows:
const [currentCoins, setCurrentCoins] = useState([])
console.log(currentCoins)
[
{
"name": "algorand",
"quantity": 1,
"currentPrice": 0
},
{
"name": "ethereum",
"quantity": 9,
"currentPrice": 0
},
{
"quantity": 4,
"name": "bitcoin",
"currentPrice": 0
}
]
I would like to add a dynamic value from an API in my currentPrice, but I'm not sure how to go about and organize this.
I had thought of something like this but it's incomplete, and I don't know how to pass the name to the API
useEffect(() => {
setCurrentCoins(coinsCopy) // update currentCoins array from another array that can be updated by the user
const fetchPrices = async (name) => {
await fetch(
`https://api.coingecko.com/api/v3/coins/${name}`
)
// this endpoint returns the current price to res.market_data.current_price.usd
.then((res) => res.json())
.then((res) => {
// processing here?
});
};
fetchPrices();
}, [coins])
Processing should be added to the "// processing here?comment or am I going in the wrong direction?
The goal would be for this to override the "0" value of currentPrice for each of my objects.
useEffect(() => {
setCurrentCoins(coinsCopy) // update currentCoins array from another array that can be updated by the user
fetchPrices();
}, [coins])
const fetchPrices = async () => {
var copyArray = [...currentCoins];
for(let c of copyArray ){
var res = await fetch(
`https://api.coingecko.com/api/v3/coins/${c.name}`
)
if(res.ok){
var data = await res.json()
var currentPriceUSD = data.market_data.current_price.usd
c.currentPrice = currentPriceUSD
}else{
console.log("Cannot find the coin");
}
}
setCurrentCoins(copyArray)
};