Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Cómo pasar un objeto obtenido de App.js a un componente secundario de forma asincrónica en ReactJS v16+

TL;DR

¿Cómo pasar un objeto obtenido de App.js a un componente secundario de forma asíncrona?

¿Tengo que esperar a que se obtengan todos los datos y luego devolver App.js? ¿Si es así, cómo?


Estoy tratando de crear un tablero con react-chartjs-2 donde obtiene datos del servidor como un objeto completo, sin embargo, el gráfico se carga antes del proceso de obtención, aquí está el código:

 import './App.css'; import AvgVisitDuration from './component/AvgVisitDuration'; import Devices from './component/Devices'; import About from './component/About'; let stats; let devices = []; async function getStats() { const response = await fetch('http://192.168.1.4:8080/api'); const data = response.json(); stats = data; getDevices(); } function getDevices() { // Set 'devices' as a new array based on 'stats' } function App() { getStats(); return ( <div className='container'> <About /> <AvgVisitDuration /> <Devices Data={devices} /> // This is the chart component </div> ); } export default App;

aquí tenemos estadísticas como el objeto obtenido y extrajimos parte de la información (como stats.isMobile) en una nueva matriz llamada dispositivos. pero el problema aquí es que cuando paso la variable de dispositivos como accesorios al componente <Devices /> , solo devuelve una matriz vacía (la que se declara primero).

Le agradecería que me dijera que hay algún otro enfoque para esto.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Creo que te estás perdiendo mucho sobre los fundamentos de React y deberías leer los documentos que tienen muchos ejemplos y patrones. Lo que quiere hacer es asegurarse de que su componente pueda manejar un estado de "carga". Las solicitudes asincrónicas no son inmediatas y toman tiempo, ¿cómo se verá su componente mientras espera que se complete la solicitud?

Estoy usando una variable de estado para rastrear la finalización de la solicitud. También recomendaría buscar cómo funciona useEffect para comprender mejor este fragmento.

 import AvgVisitDuration from './component/AvgVisitDuration'; import Devices from './component/Devices'; import About from './component/About'; import { useEffect, useState } from 'react'; function App() { const [devices, setDevices] = useState([]) const [loadingDevices, setLoadingDevices] = useState(false) useEffect(() => { async function getStats() { setLoadingDevices(true) try { const response = await fetch('http://192.168.1.4:8080/api'); const data = response.json(); const transformData = ... // do whatever you need to do to extract the data you need from the async call setDevices(transformData) setLoadingDevices(false) } catch(e) { setLoadingDevices(false) } } getStats(); }, [setStats, setLoadingDevices]) return ( <div className='container'> <About /> <AvgVisitDuration /> {loadingDevices ? <div>loading ...</div> : <Devices Data={devices} />} </div> ); } export default App;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!