skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER
    function convert() {
    const fromRate = info[from]?.usd;
    const toRate = info[to]?.usd;
    const convertedAmount = (input / fromRate) * toRate;
    setOutput(convertedAmount);
     }
    

    that's the whole point. there are two dropdowns and I do the conversion with this conversion. but if I make console.log(typeof fromRate) I get "undefined" instead of number.


  2. I cannot clearly understand the question too, but I have worked on a project that uses data from Coingecko API, so the api’s that I’ve used to get the price are below.
    For a single coin:

    const url = `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`;
    

    For multiple coins:

    const url = `https://api.coingecko.com/api/v3/simple/price?ids=${str}&vs_currencies=usd`;
    

    where str is:

    var str = coinIds.Join(",");
    

    and coinIds is an array of id’s of the coins you want to include in the response.

    Here you can find the whole documentation where you can test each api and find the appropriate one: https://www.coingecko.com/en/api/documentation

    Make sure you get the response back before you try to convert. You can also try to select a currency in the api just as in the example above instead of making the conversion manually.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search