Tengo una matriz de objetos almacenados en un estado actual de currentCoins de la siguiente manera:
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 } ] Me gustaría agregar un valor dinámico de una API en mi currentPrice , pero no estoy seguro de cómo organizarlo.
Había pensado en algo como esto pero está incompleto y no sé cómo pasar el name a la 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]) El procesamiento debe agregarse al comentario "// processing here? O voy en la dirección equivocada?
El objetivo sería que esto anule el valor "0" de currentPrice para cada uno de mis objetos.
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) };