I have a single page application where I want to display json data fetched from an url API and display said data within my rendered Table. Whats the best way to do so from the code I have below.
function App() {
const marURL = "https://blah/getMarkets.php";
function PullJson() {
fetch(marURL)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
// **MarketData = responseData?**
});
}
useEffect(() => {
PullJson();
}, []);
return (
<div className="App">
<header className="App-header">Admin Market Data Collection</header>
<table>
<thead>
<tr>
<th>Market</th>
<th>Market ID</th>
<th>Market Alpha</th>
<th>Completion Time</th>
<th>Start Time</th>
</tr>
{MarketData.map((market) => {
return (
<tr>
<td>{market.marketName}</td>
<td>{market.marketId}</td>
<td>{market.marketAlpha}</td>
<td>{market.completionTime}</td>
<td>{market.startTime}</td>
</tr>
);
})}
</thead>
</table>
</div>
);
}
The issue lies within the way to get the fetched object to a var called marketData which is being mapped. I want to render json data in the render call. Need some sort of global variable called MarketData
How do I go about that?
CodePudding user response:
Make marketData
a state atom with useState
and set
the fetched data into it.
I've opted for []
, an empty array, as the default for marketData
here, but you might want to consider null
(with a guard such as if(marketData === null) return <>Loading...</>
) to avoid flashing an empty table at your user.
(This is a simplified example that's missing e.g. error handling; you might want to look at SWR for a better data-fetching hook.)
const marURL = "https://blah/getMarkets.php";
function App() {
const [marketData, setMarketData] = useState([]);
useEffect(() => {
fetch(marURL)
.then((response) => response.json())
.then(setMarketData);
}, []);
return (
<div className="App">
<header className="App-header">Admin Market Data Collection</header>
<table>
<thead>
<tr>
<th>Market</th>
<th>Market ID</th>
<th>Market Alpha</th>
<th>Completion Time</th>
<th>Start Time</th>
</tr>
{marketData.map((market) => {
return (
<tr>
<td>{market.marketName}</td>
<td>{market.marketId}</td>
<td>{market.marketAlpha}</td>
<td>{market.completionTime}</td>
<td>{market.startTime}</td>
</tr>
);
})}
</thead>
</table>
</div>
);
}
CodePudding user response:
You can use State in react instead of Global Variable.
const [MarketData,setMarketData] = useState([])
fetch(marURL)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
setMarketData(responseData)
});