0

I am doing a react project in which I have the database in firebase, In this page I want to show the data from 2 collections: One is 'user' data and other is 'product' data. The product collection has the data of the user who posted the product. Now when displaying the product details I want to take the user data by matching the userid from product collection and display the details of the user given in user collection. This is what I tried but this shows an error like: Uncaught TypeError: Cannot read properties of undefined (reading 'url')

  const [userDetails,setUserDetails]=useState()
  const {postDetails}= useContext(PostContext)
  const {firebase}= useContext(FirebaseContext)
  useEffect(()=>{
    const {userId}=postDetails //userId is saved in products collection & it is the id of the user in users collection.
     firebase.firestore().collection('users').where('id','==',userId).get().then((res)=>{
      res.forEach(doc => {
        setUserDetails(doc.data)
      });
    })
  },[])
  return (
    <div className="viewParentDiv">
      <div className="imageShowDiv">
        <img src={postDetails.url} alt="" />
      </div>
      <div className="rightSection">
        <div className="productDetails">
          <p>&#x20B9; {postDetails.price}</p>
          <span>{postDetails.name}</span>
          <p>{postDetails.category}</p>
          <span>{postDetails.createdAt}</span>
        </div>
          <div className="contactDetails">
          <p>Seller details</p>
          <p>{userDetails.username}</p>
          <p>{userDetails.phone}</p>
        </div>
      </div>
    </div>
  );

The data in product collection:

category: "smartphone"
createdAt: "Sun Aug 07 2022 21:04:35 GMT+0530 (India Standard Time)"
name: "Mi 12 ultra"
price: "60000"
url: "https://firebasestorage.googleapis.com/v0/b/olxclone-c98d0.appspot.com/o/image%2FMi_12_ultra.jpg?alt=media&token=418f13e4-c5fc-41a0-b6bd-f3696eba2231"
userId: "34qCfu4g3oakEec0LVMvoJYXUb43"

The data of the user with above id:

id: "34qCfu4g3oakEec0LVMvoJYXUb43"
phone: "9120834756"
username: "king"

I want to display the data of the user when the product is viewed dynamically. I couldn't find an answer to this. How do I do it?

Sojo C Johny
  • 126
  • 8

0 Answers0