Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop and render elements in React after we got the data from the backend?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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} />)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading