Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
How to pass an async object to a props in react?

I'm practicing react and how to incorporate react to firebase/firestore. Now I want to make something like a CMS using firestore database. I have successfully fetch data from the database and confirmed it by console log. But the problem is whenever I tried to pass the object to be used as my props it throws me an error. But if I add the code after the page is fully loaded, the data is successfully loaded and throws me an error after I refresh the page.

I think it has something to do with asynchronous request but I don't know how to pull it off.

const app = initializeApp(firebaseConfig)

const db = getFirestore(app);

const [data, setData] = useState({});

const fetchData =async () => {

  
        const docRef = doc(db, "data", "RSVp8ljO95Dpwa0oSs0G");

        const docSnap =  await getDoc(docRef);

        const dataTest = docSnap.data();

        await setData(dataTest);
        console.log("Document data:", dataTest);
}


useEffect(() => {
    fetchData();
}, [])



return (
    
    <div style={{overflow: 'hidden'}}>
        <NavBar />           


            <div style={{width: '100%', height:'81vh', padding: '5%', overflow:'scroll'}}>
            
                <Container >

                    <div className="d-flex flex-wrap justify-content-center">    
                       
                        <TrainingSchedule 
                            **date={data.event1.date} //I want to pass the object here but throws me an error**
                            month='SEPT' 
                            eventTitle='Lets Get to know each other' 
                            eventDescription='Have a drink with our finest coach and enjoy the summer' 
                            time='1pm'
                            backgroundColor= 'CadetBlue'
                        />

......

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

please provide us with the error so that we can fully understand the problem. but for now, try this :

date={data.event1.date || null} this should cause the date to become null if the data is not ready, then get updated in the next render which is caused by setState.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Hi @Juls: Welcome to StackOverflow.

In your example, you're trying to access properties on data that don't exist in the first render (before the effect hook runs). That's why you're getting the error. Instead, check to make sure the object and properties that you need exist before trying to access them:

<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.15.7/babel.min.js"></script>

<div id="root"></div>

<script type="text/babel" data-type="module" data-presets="env,react">

const {useEffect, useState} = React;

async function getDataFromAPI () {
  await new Promise(res => setTimeout(res, 1000));
  return { event1: { date: '2021-09-18' } };
}

function Example () {
  // Leave the state value undefined instead of initializing it as an empty object
  const [data, setData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      const fetchedData = await getDataFromAPI();
      setData(fetchedData);
    };
    fetchData();
  }, []);

  return (
    <div>
      {
        // Check if the data exists before trying to access its properties:
        data
          ? (<div>{data.event1.date}</div>)
          : (<div>Data is being fetched...</div>)
      }
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda