Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
Trying to render a MUI Grid dynamically in React

I first make a request to a MongoDB server to get data from a database, all asynchronously and return a promise in App.js.

Then I pass that as a prop in my Card.js component and use .then() to get the data and push it into a new array. (I'm not sure if this is the best way to do this)

Right now I'm trying to display the names in the data dynamically using an MUI Grid, I am having problems as it shows that the data is in my array but I get no Cards on the UI. What am I doing wrong?

Card.js

import * as React from 'react';
import Grid from '@mui/material/Grid';
import RoomCard from './RoomCard'
import { useState } from 'react';

export default function Card({rooms}){
    const [loading, setLoading] = useState(false);
    let roomData = [];
    rooms.then(roomNames => { 
      roomNames.map(room => roomData.push(room)); 
    })
    console.log(roomData);
    
    return(<Grid container spacing={2}>
            {roomData.map(room => 
                <Grid item key={room} xs ={4}>
                  <RoomCard name = {room.name} />
                </Grid>
            )}
          </Grid>
    );

}

App.js

import './App.css';
import Navbar from './components/NavBar';
import AddRoom from './components/AddRoom'
import RoomCard from './components/RoomCard'
import Grid from '@mui/material/Grid';
import Cards from './components/Cards'

function App() {
  let rooms = getRecords();
  return (
    <div className="App">
        <Navbar/>
        <AddRoom/>
        <Cards rooms = {rooms} />
    </div>
  );
}


async function getRecords() {
  const response = await fetch(`http://localhost:5000/room/`);

  if (!response.ok) {
    const message = `An error occured: ${response.statusText}`;
    window.alert(message);
    return;
  }

  const rooms = await response.json();
  
  return rooms;
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

On my opinion App.js should be Higher order component (HOC) for Card.js so that Card.js is easily resusable for each room as your code may have it, the App.js should contain the loading controller. And you cannot call getRecords sync except inside an async and await function and you can use it inside a useEffect function since you are using function react function component, your code should be like this now

import React,{useEffect,useState} from 'react'
import './App.css';
import Navbar from './components/NavBar';
import AddRoom from './components/AddRoom'
import RoomCard from './components/RoomCard'
import Grid from '@mui/material/Grid';
import Cards from './components/Cards'

function App() {
  const [loading,setLoading] useState(false);
  const [rooms, setRooms] useState([]);
  useEffect(()=>{
     async fetchRooms(){
        try{
            setLoading(true)
            const fetchedRooms = await getRecords();
            setRooms(fetchedRooms);
            setLoading(false)
        }catch{
          setLoading(false)
        }
     }

     fetchRooms();
     
  },[])// the empty array is used to pass value that will make this function to be called if they changed, since its empty this useffect only gets called when component is mounted
  
  return (
    <div className="App">
        { loading && (<p>loading.....</p>) }
        <Navbar/>
        <AddRoom/>
        <Cards rooms = {rooms} />
    </div>
  );
}


async function getRecords() {
  const response = await fetch(`http://localhost:5000/room/`);

  if (!response.ok) {
    const message = `An error occured: ${response.statusText}`;
    window.alert(message);
    return;
  }

  const rooms = await response.json();
  
  return rooms;
}

export default App;

And inside your card.js you should have something like this

import * as React from 'react';
import Grid from '@mui/material/Grid';
import RoomCard from './RoomCard'
import { useState } from 'react';

export default function Card({rooms}){
   
    return(<Grid container spacing={2}>
            {rooms.map(room => 
                <Grid item key={room} xs ={4}>
                  <RoomCard name = {room.name} />
                </Grid>
            )}
          </Grid>
    );

}

This makes sure your card.js is clean

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda