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

162
Visualizações
Conditionally rendering tables from an API

I need help rendering the table headers and the parsed information from an API only when the button is pressed. Along with refreshing the page when a different button is pressed so the array of 100+ objects don't stack on top of each other. I am using React to write this code. There is more to this code but this is a snippet and I want to apply it to the other buttons (3).

I'm also thinking of creating a new file for each API call to get their information and then importing them into this file to be enacted when the button gets pressed.

import { useState } from 'react';

export default function Markets() {
  const API_KEY = process.env.REACT_APP_MS_API_KEY;
  const [dataEndOfDay, setEndOfDay] = useState('');

  async function getEndOfDay() {
    try {
      const response = await axios.get(
        `${BASE_URL}eod?access_key=${API_KEY}&symbols=AAPL`
      );
      console.log(response.data.data);
      setEndOfDay(
        response.data.data.map((row) => {
          return (
            <tr>
              <td>{row.date}</td>
              <td>{row.symbol}</td>
              <td>${row.open}</td>
              <td>${row.close}</td>
            </tr>
          );
        })
      );
    } catch (error) {
      console.error(error);
    }
  }


  return (
    <div className="market-button">
      <button onClick={getEndOfDay}>Get End of Day Report</button>

      <table>
        <tr>
          <th>Date</th>
          <th>Symbol</th>
          <th>Open</th>
          <th>Close</th>
        </tr>
        {dataEndOfDay}
      </table>
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You just need to wrap your table inside of an if statement. But also remove the empty string from your state and just leave it empty or set it to null.

 const [dataEndOfDay, setEndOfDay] = useState();

 return (
    <div className="market-button">
      <button onClick={getEndOfDay}>Get End of Day Report</button>

     { dataEndOfDay && 
      <table>
        <tr>
          <th>Date</th>
          <th>Symbol</th>
          <th>Open</th>
          <th>Close</th>
        </tr>
        {dataEndOfDay}
      </table>
     }
     <div>
)


But on another note your code isn't the best for performance and I would recommend refactoring it. You shouldn't save the html data for your rows in state but rather just the data from the api and then just loop over it in the render.

import { useState } from 'react';

export default function Markets() {
  const API_KEY = process.env.REACT_APP_MS_API_KEY;
  const [dataEndOfDay, setEndOfDay] = useState();

  async function getEndOfDay() {
    try {
      const response = await axios.get(`${BASE_URL}eod?access_key=${API_KEY}&symbols=AAPL`);
      console.log(response.data.data);
      setEndOfDay(response.data.data);
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div className="market-button">
      <button onClick={getEndOfDay}>Get End of Day Report</button>

      {
        dataEndOfDay && 
        <table>
        <tr>
          <th>Date</th>
          <th>Symbol</th>
          <th>Open</th>
          <th>Close</th>
        </tr>
        {
          dataEndOfDay.map(row => {
            return (
              <tr>
                <td>{row.date}</td>
                <td>{row.symbol}</td>
                <td>${row.open}</td>
                <td>${row.close}</td>
              </tr>
            );
          }
        }
      </table>
      }
    </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