Home > Software engineering >  Uncaught TypeError: Cannot read properties of undefined (reading 'map') while using map fu
Uncaught TypeError: Cannot read properties of undefined (reading 'map') while using map fu

Time:12-14

useEffect(() => {
        if(currentUser){
            currentUser?.friends.map(friends => {
                if(friends._id===currentProfile._id){
                    return setFriend(true)
                }
            })
        }else{
            return setFriend(false)
        }
    },[currentUser,currentProfile])

//currentUser is the user logged in
//currentProfile is user selected

i want to show button as Unfriend if the user selected is already a friend.Iam trying to use a map function to find if the user is already a friend.but the map function is shown as error

CodePudding user response:

Looks to me like currentUser is defined but doesn't have a property currrentUser.friends. Try currentUser?.friends?.map(...)

And change the else clause to always return instead. If return setFriend(true) was called, the return friend(false) won't be called, but in all other cases.

CodePudding user response:

Since you have the if statement we already know that currentUser exists you will have to see if the currentUser have friends. However map should be used to create a new array, you use it to iterate over friends. You could simplify the whole useEffect with some instead

useEffect(() => {
  setFriend(
    currentUser &&
      currentUser.friends?.some((friends) => friends._id === currentProfile._id)
  );
}, [currentUser, currentProfile]);

If currentUser is a value and a friend have the same id as currentProfile

  • Related