Search code examples
javascriptreactjsasync-awaitreact-props

How can I pass props after fetching from database?


I am using Firebase as backend and the schema is as following

const sample_data = {
  Name: "",
  Address: "",
  Contact_no: "",
  Email: "",
  img_url: ""
}

First of all I am fetching with asyncfunction like this

FetchList.js


let dummy = {}

async function getItems(){
    const response = await fetch('realtime__database__of__firebase__url');
    
    if (!response.ok) {
        throw new Error("Something went wrong");
      }
  
      dummy = await response.json();
}
getItems();
export default dummy;

then I'm passing the retrieved data to my card component like this.

ListHospital.js

import Card from "../UI/Card";
import dummy from "./FetchList";


const ListHospitals = () => {
    return <Card>
        {dummy}
    </Card>
}

export default ListHospitals;

Finally I want to access all data that I passed as props in my CARD component, but when I console.log here the output is undefined and when I console.log after fetching the data it gives suitable output. The problem I'm getting is the FetchList component is being exported before fetching the data.

Card.js

import classes from "./Card.module.css";


const Card = (props) => {

    let url = props.children.img;
    console.log(url);
    return <div>
                <img src={props.children.img} alt={props.children.Name}></img>

                <h1 >{props.children.Name}</h1>
                <p>{props.children.Address}</p>
                <h3 >Contact</h3>
                <p>{props.children.Email}</p>
                <p>{props.children.Contact_no}</p>

</div>
}

export default Card;

Solution

  • FetchList isn't a React component. You should be doing the data fetching from a React component lifecycle method or useEffect hook when the component mounts (or as needed on-demand).

    Export the getItems function:

    async function getItems(){
      const response = await fetch('realtime__database__of__firebase__url');
        
      if (!response.ok) {
        throw new Error("Something went wrong");
      }
      
      return response.json();
    }
    
    export default getItems;
    

    Load when the component mounts. Pass the data as a prop to Card instead of as children.

    import { useEffect, useState } from 'react';
    import Card from "../UI/Card";
    import getItems from "./FetchList";
    
    const ListHospitals = () => {
      const [data, setData] = useState({});
    
      useEffect(() => {
        getItems()
          .then(data => setData(data))
          .catch(error => {
            // fetch can return rejected Promise, maybe handle it?
          });
      }, []);
    
      return <Card data={data} />;
    }
    

    Card - access the data prop.

    const Card = ({ data }) => {
      const url = data.img;
      console.log(url);
    
      return (
        <div>
          <img src={data.img} alt={data.Name} />
          <h1 >{data.Name}</h1>
          <p>{data.Address}</p>
          <h3>Contact</h3>
          <p>{data.Email}</p>
          <p>{data.Contact_no}</p>
        </div>
      );
    }