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

Time:01-11

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>

CodePudding user response:

try to change something like this. The thing is pushing item to the const buildings = [] has no effect. So you need to use useState hook

import React, { useEffect, useState } from 'react';
import BuildingItem from './components/buildingItem';
import { Config } from './config/config';

export default function Buildings() {

  const [buildings, setBuildings] = useState([]);

  useEffect(() => {
    fetch(Config.domain   'kingdom/buildings', {
      headers: { 'Authorization': 'Bearer '   localStorage.getItem('token') }
    })
      .then(res => res.json())
      .then(data => setBuildings(data))
  })

  return (
    <div className='buildings'>
      <div className='buildings-container'>
        {buildings.map((item)=> (
          <BuildingItem type={item.type} level={item.level} />
        )}
      </div>
    </div>
  );
}

CodePudding user response:

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} />)
}
  •  Tags:  
  • Related