Skip to content
Snippets Groups Projects
useFriends.ts 1.14 KiB
Newer Older
Matt Kirby's avatar
Matt Kirby committed
import { useState, useEffect } from "react"

export const useFriends = () => {
  const [friends, setFriends] = useState<Map<string, any> | undefined>(undefined)

  const fetchFriends = async () => {
    const endpoint = `${process.env.NEXT_PUBLIC_FRIEND_SERVICE_URL}friends`

    const headers =  {'Authorization': `Bearer ${sessionStorage.getItem("token")}`}
    const response = await fetch(endpoint, {headers})
    return await response.json()

  
  }

  const fetchUserList = async (userIdList: string[]) => {
    const endpoint = `${process.env.NEXT_PUBLIC_USER_SERVICE_URL}api/userlist`

    console.log(userIdList, true)
    
    const JSONdata = JSON.stringify({
      userIdList
    })
    const options = {
      method: 'POST',
      headers: {'Content-Type': 'application/json',},
      body: JSONdata,
    }
    
    const response = await fetch(endpoint, options)
    return await response.json()
  }

  useEffect(() => {
    if(friends === undefined){
      fetchFriends().then(res => {
        fetchUserList(res.result).then(userlistRes => {
          setFriends(new Map(userlistRes.userList))
        })
        
      })
    }
  })
  return friends 
}