Skip to content

Commit

Permalink
fix : follow page
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedrinvits committed Nov 12, 2024
1 parent 46ed65a commit 7ee24ff
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 56 deletions.
40 changes: 39 additions & 1 deletion data/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,42 @@ export const getUsers = async (limit ?: number) => {
}catch(error){
return null
}
}
}

export const getUsersNotFollowing = async (userId: number) => {

try {
// Busca todos os usuários que o usuário atual está seguindo
const followedUsers = await db.following.findMany({
where: {
followerId: Number(userId)
},
select: {
followingId: true // Pegamos o ID dos usuários seguidos
}
})

// Coletando os IDs dos usuários seguidos
const followedUserIds = followedUsers.map(follow => follow.followingId)

// Busca todos os usuários que não estão na lista de seguidos
const usersNotFollowing = await db.user.findMany({
where: {
id: {
not: Number(userId),
},
NOT: {
id: {
in: followedUserIds
}
}
}
})

return usersNotFollowing
} catch (error) {
console.error('Erro ao buscar usuários não seguidos:', error)
throw new Error('Erro ao buscar usuários não seguidos')
}

}
107 changes: 52 additions & 55 deletions src/app/(app)/follow/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Search, UserPlus, Check, Loader2 } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { getUserByUsername, getUsers } from "../../../../data/user"
import { getUserByUsername, getUsers, getUsersNotFollowing } from "../../../../data/user"
import SuggestedUsers from "@/components/sugested-users"
import { useSession } from "next-auth/react"
import { toast } from "@/hooks/use-toast"
Expand All @@ -13,11 +13,11 @@ import { followUser, unfollowUser } from "../../../../data/following/followUser"

export default function Component() {
const [searchTerm, setSearchTerm] = useState("")
const [searchResults, setSearchResults] = useState<User[]>([])
const [searchResults, setSearchResults] = useState<User | null>(null)
const [users, setUsers] = useState<User[]>([])
const [addedFriends, setAddedFriends] = useState<number[]>([])
const [isSearching, setIsSearching] = useState(false)
const [usuarioBuscadoJaEhSeguido, setusuarioBuscadoJaEhSeguido] = useState(false)
const [followStatus, setFollowStatus] = useState<Map<number, boolean>>(new Map()) // Mapa de estado de follow
const { data } = useSession()
const current_user_id = data?.id;

Expand All @@ -36,20 +36,20 @@ export default function Component() {
}
if (results.id == current_user_id) {
toast({
title: 'The user you are search cannot be you',
title: 'The user you are searching cannot be you',
description: 'Please try another user that is not you'
})
return
}

if(results?.following !== '' && (results?.following[0]?.followerId == current_user_id)){
setusuarioBuscadoJaEhSeguido(true)
}
console.log(results);

// Verifica se o usuário já está seguido
if (results?.following !== '' && (results?.following[0]?.followerId == current_user_id)){
setFollowStatus(prev => prev.set(results.id, true))
} else {
setFollowStatus(prev => prev.set(results.id, false))
}

setSearchResults(results)


} catch (error) {
console.error("Error searching users:", error)
} finally {
Expand All @@ -58,41 +58,46 @@ export default function Component() {
}

const handleAddFriend = async (userId: number) => {
// colocar funcao pra gravar a amizade
// if (!addedFriends.includes(userId)) {
if (!usuarioBuscadoJaEhSeguido) {
setAddedFriends([...addedFriends, userId])
const res = await followUser(userId)
if(res.success){
setusuarioBuscadoJaEhSeguido(true)

const isFollowed = followStatus.get(userId);

if (!isFollowed) {
// Seguindo o usuário
setFollowStatus(prev => prev.set(userId, true));
const res = await followUser(userId);
if (res.success) {
setUsers((prevUsers) => prevUsers.filter(user => user.id !== userId));
toast({
title : "Your follow this user now!"
})
title: "You followed this user now!"
});
}
console.log('if pra seguir');
}else{
const res = await unfollowUser(userId)
if(res.success){
setusuarioBuscadoJaEhSeguido(false)
} else {
// Deixando de seguir
setFollowStatus(prev => prev.set(userId, false));
const res = await unfollowUser(userId);
if (res.success) {
// setUsers((prevUsers) => [...prevUsers, users.find(user => user.id === userId)!]);
setAddedFriends((prevFriends) => prevFriends.filter(friendId => friendId !== userId));
toast({
title : "Your unfollow this user now!"
})
title: "You unfollowed this user now!"
});
}
console.log('else pro unfollow');
}


}

useEffect(() => {
const fetch = async () => {
const res = await getUsers()
console.log('res = ',res);
setUsers(res)
const res = await getUsersNotFollowing(current_user_id);
setUsers(res);

// Inicia o estado de follow para todos os usuários na lista de sugeridos
res.forEach(user => {
// Verifique se o usuário está sendo seguido ou não
setFollowStatus(prev => prev.set(user.id, false));
});
}
fetch()
}, [])
// console.log(users);
fetch();
}, []);

return (
<div className="w-full max-w-md mx-auto p-4 space-y-4">
Expand All @@ -112,7 +117,7 @@ export default function Component() {
</Button>
</div>

{searchResults != '' ? (
{searchResults && (
<div className="space-y-4">
<h2 className="text-xl font-bold">Search Results</h2>

Expand All @@ -128,12 +133,11 @@ export default function Component() {
</div>
</div>
<Button
variant={usuarioBuscadoJaEhSeguido ? "secondary" : "default"}
variant={followStatus.get(searchResults.id) ? "secondary" : "default"}
size="sm"
onClick={() => handleAddFriend(searchResults.id)}
// disabled={addedFriends.includes(searchResults.id)}
>
{usuarioBuscadoJaEhSeguido? (
{followStatus.get(searchResults.id) ? (
<>
<Check className="h-4 w-4 mr-1" />
Unfollow
Expand All @@ -146,21 +150,16 @@ export default function Component() {
)}
</Button>
</div>

</div>
) : (
<></>
)
)}

}
<div className="flex flex-col gap-4 mt-4">
<h1 className="mt-4">Suggested Users</h1>
{
users.map((e)=>
<div key={e.id} className="flex items-center justify-between hover:bg-muted p-3 rounded-lg border shadow-lg">
{users.map((e) => (
<div key={e.id} className="flex items-center justify-between hover:bg-muted p-3 rounded-lg border shadow-lg">
<div className="flex items-center space-x-3">
<Avatar>
<AvatarImage src={e.profileImageUrl} alt={e.username} />
<AvatarImage src={e.profileImageUrl? e.profileImageUrl : ''} alt={e.username} />
<AvatarFallback>{e.username?.charAt(0)}</AvatarFallback>
</Avatar>
<div>
Expand All @@ -169,12 +168,11 @@ export default function Component() {
</div>
</div>
<Button
variant={usuarioBuscadoJaEhSeguido ? "secondary" : "default"}
variant={followStatus.get(e.id) ? "secondary" : "default"}
size="sm"
onClick={() => handleAddFriend(e.id)}
// disabled={addedFriends.includes(searchResults.id)}
>
{usuarioBuscadoJaEhSeguido? (
{followStatus.get(e.id) ? (
<>
<Check className="h-4 w-4 mr-1" />
Unfollow
Expand All @@ -187,9 +185,8 @@ export default function Component() {
)}
</Button>
</div>
)
}
))}
</div>
</div>
)
}
}

0 comments on commit 7ee24ff

Please sign in to comment.