1

I'm trying to create a useState hook that contains an array of a user's friends. To access this friend list, I'm grabbing the array from the firebase database. However, when I try to update the useState, it still logs friendList as undefined. If I log the values, it tries to add them and appears fine.

function SideBarFriends (props: any) {
  const { sbView, setSbView } = useContext(ViewContext);
  const [friendList, setFriendList] = useState<string[]>();
    useEffect(() => {
      getFriends()
    }, [])
  
  function getFriends() {
    setFriendList(null);
    const query = userRef.where('uid', '==', auth.currentUser.uid);
    query.get().then((snapshot) => {
      snapshot.forEach((doc) => {
        const { friends } = doc.data();
        friends.map((f: string) => updateFriends);
      })
    })

  
  function updateFriends(item: any) {
    if (!friendList) {
      setFriendList([item]);
      return;
    }
    else {
      setFriendList(friendList => [...friendList, item])
      return;
    }
  }
 }
  return(
    <section>
      <FontAwesomeIcon className='text-white/70 pl-4' icon={faMagnifyingGlass} onClick={() => {setSbView(false)} } />
    </section>
  )
}

I'm struggling for ideas here as I did a similar function for my search user function, which works with no issues.

Sujith Sandeep
  • 1,185
  • 6
  • 20

3 Answers3

0

You are not calling updateFriends in your code. Your map function is effectively a no-op.

Change it to

friends.map((f: string) => updateFriends(f));
Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43
0

Actually, you set value asynchronously so when you directly use this array it will show undefined even when you console.log(friendList) first it will show undefined then it will show array of friendList. For this you can use optional chaining for iterating or any other operation Example for iterating friendList:

friendList?.map((item,index)=>{
    return(<p>{item}</p>)  
})

and in you case as you are using:

friends?.map((f: string) => updateFriends(f));
0

Your function heirarchy is wrong

You are defining updateFriends inside getFriends So updateFriends() is not executed

Your Present code:

|_getFriend()
 |_ updateFriends()  It is defined but never called

Change it to :

|_getFriend()
|_updateFriends()

Change

  function getFriends() {
   ...

  function updateFriends(item: any) {
   ...
  }
 }

To

  function getFriends() {
   ...
  }
  function updateFriends(item: any) {
   ...
  }

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88