'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>
}
Solution 1:[1]
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>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
