Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda