I'm trying to implement a simple crypto coin converter. Trying to do it with coingecko API and react. Anyway, I get the coins listed on the dropdown, but the convert function, the main thing, isn't work. I don't know which endpoint of coingecko I should use, so I guess that's the whole point. Does anybody knows how to do it? Anyway, here is the code:
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import Dropdown from 'react-dropdown';
import { HiSwitchHorizontal } from 'react-icons/hi';
import 'react-dropdown/style.css';
import './App.css';
function App() {
const [info, setInfo] = useState({});
const [input, setInput] = useState(0);
const [from, setFrom] = useState('ethereum');
const [to, setTo] = useState('bitcoin');
const [options, setOptions] = useState([]);
const [output, setOutput] = useState(0);
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
// Fetch the list of supported coins from Coingecko
const fetchCoinsList = async () => {
try {
const response = await Axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd');
const coinsList = response.data.map((coin) => coin.id);
setOptions(coinsList);
} catch (error) {
console.error('Error fetching supported coins list:', error);
}
};
fetchCoinsList();
}, []);
useEffect(() => {
// Fetch data from Coingecko for the selected coins
const fetchData = async () => {
try {
const response = await Axios.get(
`https://api.coingecko.com/a0pi/v3/simple/price?ids=${from}}&vs_currencies=${to}`
);
const data = response.data;
setInfo(data);
} catch (error) {
console.error('Error fetching data from Coingecko:', error);
}
};
console.log(from);
console.log(to);
fetchData();
}, [from, to]);
function convert() {
const fromRate = info[from]?.usd;
const toRate = info[to]?.usd;
const convertedAmount = (input / fromRate) * toRate;
setOutput(convertedAmount);
}
function flip() {
const temp = from;
setFrom(to);
setTo(temp);
}
return (
<div className="App">
<div className="aba">
<h1>Currency converter</h1>
<h3>Amount</h3>
<input
type="text"
placeholder="Enter the amount"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<h3>From</h3>
<Dropdown
options={options}
onChange={(e) => setFrom(e.value)}
value={from}
placeholder="From"
/>
<HiSwitchHorizontal className='swap' size="25px" onClick={() => flip()} />
<h3>To</h3>
<Dropdown
options={options}
onChange={(e) => setTo(e.value)}
value={to}
placeholder="To"
/>
<button className='botao' onClick={() => convert()}>Convert</button>
</div>
<div className='aba'>
<h2>Converted Amount:</h2>
<p>
{input} {from} = {output.toFixed(2)} {to}
</p>
</div>
</div>
);
}
export default App;
``````
the main part is the convert function. console.log(fromRate) or toRate shows me undefined and the convertedAmout is NaN.
a function that calls the right endpoint.