求可实时将ETH余额转换为AVAX价格的API(Next.js应用场景)
实现ETH到AVAX的实时价值转换(基于CoinGecko API)
你完全可以用CoinGecko API实现ETH到AVAX的实时转换,核心是利用它的Simple Convert接口,无需手动计算价格比值。以下是具体实现方案:
核心思路
CoinGecko的/simple/convert接口支持直接跨币种转换,只需指定源币种ID、目标币种ID和转换金额即可。ETH的币种ID是ethereum,AVAX的币种ID是avalanche-2。
Next.js 代码实现
下面是一个实时转换的组件示例,包含防抖处理以避免频繁API请求:
import { useState, useEffect } from 'react'; export default function EthToAvaxConverter() { const [ethAmount, setEthAmount] = useState(''); const [avaxValue, setAvaxValue] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchConversion = async () => { // 校验输入有效性 const numAmount = parseFloat(ethAmount); if (!ethAmount || isNaN(numAmount)) { setAvaxValue(null); return; } setLoading(true); try { const res = await fetch( `https://api.coingecko.com/api/v3/simple/convert?from=ethereum&to=avalanche-2&amount=${numAmount}` ); const data = await res.json(); // 提取转换后的AVAX数值 setAvaxValue(data.avalanche_2); } catch (err) { console.error('转换请求失败:', err); setAvaxValue(null); } finally { setLoading(false); } }; // 500ms防抖,减少API请求次数 const debounceTimer = setTimeout(fetchConversion, 500); return () => clearTimeout(debounceTimer); }, [ethAmount]); return ( <div className="converter"> <input type="number" value={ethAmount} onChange={(e) => setEthAmount(e.target.value)} placeholder="输入ETH数量" step="0.001" min="0" /> {loading ? ( <p>加载中...</p> ) : avaxValue !== null ? ( <p>等价AVAX: {avaxValue.toFixed(4)}</p> ) : ( <p>请输入有效的ETH数值</p> )} </div> ); }
注意事项
- CoinGecko免费版API有请求频率限制(每分钟最多50次),防抖处理能有效避免触发限制。
- 如果需要更高的请求配额,可以考虑注册CoinGecko Pro账号。
- 币种ID可以通过CoinGecko的
/coins/list接口查询,确保使用正确的ID。
内容的提问来源于stack exchange,提问作者David Li
相关产品推荐
相关产品推荐

