0

I am creating a dynamic user profile and Am trying to map through an object using React.

I have this code below that fetches user data:

   projectFirestore.collection("users").onSnapshot(snapshot => (
     setUserData(snapshot.docs.map(doc => doc.data()))
   ))
 }, [])
/*when the user data is fetched I console.log it
 console.log(userData)
and it returns an array with objects like [{…}, {…}, {…}, {…}, {…}]
*/

then I search for a specific user using the array.find() method:

const findTheUser = userData.find(function(data, index) {
   if(data.email === 'minenhlecele@gmail.com')
     return true;
   });  

/* I console.log it
console.log(findTheUser)

and it returns the matching object. the result looks like this  */ 
//{name: 'Minenhle Cele', email: 'minenhlecele@gmail.com', photoUrl: 'https://lh3.googleusercontent.com/a-/AOh14Gj36jZuv0m2rxAN7Fx_78QWHbURpY-YeWb9g=s96-c'}

Then what I want is to map through the findTheUser object and display the data to the user like

{findTheUser.map(({{ name, email}}) => (
           <div className="card">
             <h1>{name}</h1>
             <h2>{email}</h2>
           </div>
            ))}

But it keeps throwing the

TypeError: Cannot read properties of undefined (reading 'map')

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

Your findTheUser function uses Array.find which is documented as:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function

So the return value is an element from the array, and not an array itself, and the object doesn't have a map method.

So you don't need the loop, and can just do:

<div className="card">
  <h1>{findTheUser.name}</h1>
  <h2>{findTheUser.email}</h2>
</div>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I tried that method but because the object is from the API it takes time to load and react renders initially, so when react checks it finds an empty object then throws this error "TypeError: Cannot read properties of undefined (reading 'name') " – Minenhle Solson Cele Sep 18 '21 at 21:45
  • Ah, that is second problem indeed. You'll need to pass the item through `setState` (or `useState`) as I've shown [here](https://stackoverflow.com/a/65469639) and [here](https://stackoverflow.com/a/67511632/209103). – Frank van Puffelen Sep 18 '21 at 22:16
  • Hey @MinenhleSolsonCele Any update here? – Frank van Puffelen Sep 25 '21 at 20:08
  • Yes, Thank You for asking I used the conditional rendering method, {findTheUser ?

    {findTheUser.name}

    {findTheUser.email}

    : null}
    – Minenhle Solson Cele Sep 26 '21 at 14:46