Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
How do I change the data I'm getting from an API dynamically based on what button I'm clicking?

I'm creating a crypto app and I want to dynamically change all the data according to what currency I click on inside of a dropdown menu.

This is the function I use to fetch all the data for the market chart

getMarketData = async (currency) => {
try {
  const { data } = await axios.get(
    `https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=${currency}&days=30&interval=daily`
  );
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. You need two states - one to hold the selected currency, and one to hold the data returned from the API.

  2. Add a handler to the select element to listen for change events. Use the value from the selected option as the variable you use for the currency in your URI.

  3. When your data is returned update the data state

  4. Only if you have data display it.

This example uses a mock API to return some data.

const { useEffect, useState } = React;

// Mock data
const data = { cz: [1, 3, 5], en: [10, 12, 20], de: [45, 32, 34] };

// Mock API that returns data after a second
function mockApi(currency) {
  return new Promise((res, rej) => {
   setTimeout(() => res(data[currency]), 1000);
  });
}

function Example() {

  // Two states initialised with an empty array
  // for the data, and an empty string for the currency
  const [ data, setData ] = useState([]);
  const [ currency, setCurrency ] = useState('');

  // On the initial render update
  // currency state
  useEffect(() => {
    setCurrency('de');
  }, []);

  // When the currency state is updated
  // call the API
  useEffect(() => {
    if (currency) {
      mockApi(currency).then(data => setData(data));
    }
  }, [currency]);

  // When a new currency is selected
  // update the currency state with the value
  // from the option
  function handleChange(e) {
    const { value } = e.target;
    setCurrency(value);
  }

  // Show the select element and add a change 
  // handler to it. If there's data create a list,
  // otherwise show a loading/error message
  return (
    <div>
      <select onChange={handleChange}>
        <option disabled>Choose currency</option>
        <option value="en" selected={currency === "eu"}>EN</option>
        <option value="de" selected={currency === "de"}>DE</option>
        <option value="cz" selected={currency === "cz"}>CZ</option>
      </select>
      {data.length ? (
        <ul>{data.map(el => <li>{el}</li>)}</ul>
      ) : <div>No data</div>}
    </div>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda