UNPKG

bigblocks

Version:

Complete Bitcoin UI component library - authentication, social, wallet, market, inscriptions, and blockchain interactions for React

99 lines (98 loc) 3.88 kB
// useFriendRequests Hook - Manage friend requests import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useBitcoinAuth } from "../../../hooks/useBitcoinAuth.js"; import { API_ENDPOINTS, DEFAULT_SOCIAL_API_URL } from "../constants.js"; export function useFriendRequests() { const { user, isAuthenticated, config } = useBitcoinAuth(); const queryClient = useQueryClient(); const { data: requestsData = { requests: [], sentRequests: [] }, isLoading, error, refetch, } = useQuery({ queryKey: ["friendRequests", user?.idKey], queryFn: async () => { if (!user?.idKey) { throw { code: "UNAUTHORIZED", message: "User must be authenticated", }; } const apiUrl = config?.apiUrl || DEFAULT_SOCIAL_API_URL; const [requestsRes, sentRes] = await Promise.all([ fetch(`${apiUrl}${API_ENDPOINTS.FRIEND_REQUESTS_INCOMING(user.idKey)}`), fetch(`${apiUrl}${API_ENDPOINTS.FRIEND_REQUESTS_OUTGOING(user.idKey)}`), ]); if (!requestsRes.ok || !sentRes.ok) { throw { code: "NETWORK_ERROR", message: "Failed to fetch friend requests", }; } const [requests, sentRequests] = await Promise.all([ requestsRes.json(), sentRes.json(), ]); return { requests, sentRequests }; }, enabled: isAuthenticated && !!user?.idKey, staleTime: 30 * 1000, // 30 seconds refetchOnWindowFocus: false, }); const acceptMutation = useMutation({ mutationFn: async (idKey) => { if (!user?.idKey) { throw { code: "UNAUTHORIZED", message: "User must be authenticated", }; } const apiUrl = config?.apiUrl || DEFAULT_SOCIAL_API_URL; const response = await fetch(`${apiUrl}${API_ENDPOINTS.FRIEND_REQUESTS_ACCEPT}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ idKey }), }); if (!response.ok) { throw { code: "NETWORK_ERROR", message: "Failed to accept friend request", }; } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["friendRequests"] }); queryClient.invalidateQueries({ queryKey: ["friends"] }); }, }); const rejectMutation = useMutation({ mutationFn: async (idKey) => { if (!user?.idKey) { throw { code: "UNAUTHORIZED", message: "User must be authenticated", }; } const apiUrl = config?.apiUrl || DEFAULT_SOCIAL_API_URL; const response = await fetch(`${apiUrl}${API_ENDPOINTS.FRIEND_REQUESTS_REJECT}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ idKey }), }); if (!response.ok) { throw { code: "NETWORK_ERROR", message: "Failed to reject friend request", }; } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["friendRequests"] }); }, }); return { requests: requestsData.requests, sentRequests: requestsData.sentRequests, isLoading, error: error || null, acceptRequest: acceptMutation.mutate, rejectRequest: rejectMutation.mutate, refetch, }; }