How is it possible to loop through the data from the backend and render components based on it?
I’ve tried something like this:
import React, { useEffect } from 'react';
import BuildingItem from './components/buildingItem';
import { Config } from './config/config';
export default function Buildings() {
const buildings = [];
useEffect(() => {
fetch(Config.domain + 'kingdom/buildings', {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
})
.then(res => res.json())
.then(data => {
for(let i = 0; i < data.length; i++) {
buildings.push(<BuildingItem type={data[i].type} level={data[i].level} />);
}
})
})
return (
<div className='buildings'>
<div className='buildings-container'>
{buildings}
</div>
</div>
);
}
And also tried something like this when returning
<div className='buildings-container'>
{buildings.map((item)=> (
item
)}
</div>
>Solution :
Make use of state here and then map through that.
instead of this:
.then(data => {
for(let i = 0; i < data.length; i++) {
buildings.push(<BuildingItem type={data[i].type} level={data[i].level} />);
}
})
use React.useState, for example: const [data, setData] = useState() instead of const buildings = [];
.then(data => {
// create state like this for example: const [data, setData] = useState() instead of const buildings = [];
setData(data)
})
then in the jsx do something like this:
{
data.map((item, idx) => <BuildingItem type={item.type} level={item.level} />)
}