> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sublay.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Fetch Received Pending Connections

# `useFetchReceivedPendingConnections`

## Overview

The `useFetchReceivedPendingConnections` hook fetches the list of connection requests that the current logged-in user has received from other users but hasn't responded to yet. This is essential for building connection request notification systems and inbox features.

## Usage Example

```tsx theme={null}
import { useFetchReceivedPendingConnections } from "@replyke/react-js";

function MyInboxConnectionRequests() {
  const fetchReceivedPendingConnections = useFetchReceivedPendingConnections();

  const loadReceivedRequests = async () => {
    try {
      const result = await fetchReceivedPendingConnections({ page: 1, limit: 10 });

      console.log(`Found ${result.pagination.totalCount} pending requests received`);
      result.connections.forEach(connection => {
        console.log(`Request from ${connection.user.username} on ${connection.createdAt}`);
      });
    } catch (error) {
      console.error("Failed to fetch received pending connections:", error.message);
    }
  };

  return <button onClick={loadReceivedRequests}>Load Connection Requests</button>;
}
```

## Advanced Usage with Action Handling

```tsx theme={null}
import { useFetchReceivedPendingConnections, PendingConnectionListResponse } from "@replyke/react-js";
import { useState, useEffect } from "react";

function ConnectionRequestsInbox() {
  const fetchReceivedPendingConnections = useFetchReceivedPendingConnections();
  const [receivedRequests, setReceivedRequests] = useState<PendingConnectionListResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const loadReceivedRequests = async (page: number) => {
    setLoading(true);
    try {
      const result = await fetchReceivedPendingConnections({ page, limit: 12 });
      setReceivedRequests(result);
    } catch (error) {
      console.error("Failed to load received requests:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadReceivedRequests(currentPage);
  }, [currentPage]);

  const handleAcceptRequest = async (connectionId: string) => {
    // This would typically call useAcceptConnection hook
    console.log("Accepting request:", connectionId);
    // After successful acceptance, refresh the list
    loadReceivedRequests(currentPage);
  };

  const handleDeclineRequest = async (connectionId: string) => {
    // This would typically call useDeclineConnection hook
    console.log("Declining request:", connectionId);
    // After successful decline, refresh the list
    loadReceivedRequests(currentPage);
  };

  if (loading && !receivedRequests) {
    return <div>Loading connection requests...</div>;
  }

  return (
    <div className="connection-requests-inbox">
      <h2>Connection Requests ({receivedRequests?.pagination.totalCount || 0})</h2>

      {receivedRequests?.connections.length === 0 ? (
        <div className="empty-inbox">
          <div className="empty-icon">📭</div>
          <h3>No pending requests</h3>
          <p>You're all caught up! No new connection requests at the moment.</p>
        </div>
      ) : (
        <>
          <div className="requests-list">
            {receivedRequests?.connections.map(connection => (
              <div key={connection.id} className="request-card">
                <div className="requester-info">
                  {connection.user.avatar && (
                    <img
                      src={connection.user.avatar}
                      alt={`${connection.user.username} avatar`}
                      className="avatar"
                    />
                  )}
                  <div className="user-details">
                    <h4>{connection.user.displayName || connection.user.username}</h4>
                    <p>@{connection.user.username}</p>
                    <small>
                      Requested: {new Date(connection.createdAt).toLocaleDateString()}
                    </small>
                  </div>
                </div>

                {connection.message && (
                  <div className="request-message">
                    <h5>Message:</h5>
                    <p>"{connection.message}"</p>
                  </div>
                )}

                <div className="request-actions">
                  <button
                    onClick={() => handleAcceptRequest(connection.id)}
                    className="accept-btn primary"
                  >
                    Accept
                  </button>
                  <button
                    onClick={() => handleDeclineRequest(connection.id)}
                    className="decline-btn secondary"
                  >
                    Decline
                  </button>
                </div>
              </div>
            ))}
          </div>

          {receivedRequests && receivedRequests.pagination.totalPages > 1 && (
            <div className="pagination">
              <button
                disabled={!receivedRequests.pagination.hasPreviousPage || loading}
                onClick={() => setCurrentPage(prev => prev - 1)}
              >
                Previous
              </button>

              <span>
                Page {receivedRequests.pagination.currentPage} of {receivedRequests.pagination.totalPages}
              </span>

              <button
                disabled={!receivedRequests.pagination.hasNextPage || loading}
                onClick={() => setCurrentPage(prev => prev + 1)}
              >
                Next
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
```

## Usage with Notification Badge

```tsx theme={null}
import { useFetchReceivedPendingConnections } from "@replyke/react-js";
import { useState, useEffect } from "react";

function ConnectionRequestsBadge() {
  const fetchReceivedPendingConnections = useFetchReceivedPendingConnections();
  const [unreadCount, setUnreadCount] = useState<number>(0);

  useEffect(() => {
    const loadUnreadCount = async () => {
      try {
        // Just get the first page to check if there are any requests
        const result = await fetchReceivedPendingConnections({ page: 1, limit: 1 });
        setUnreadCount(result.pagination.totalCount);
      } catch (error) {
        console.error("Failed to load connection requests count:", error);
      }
    };

    loadUnreadCount();

    // Set up periodic refresh (every 30 seconds)
    const interval = setInterval(loadUnreadCount, 30000);
    return () => clearInterval(interval);
  }, [fetchReceivedPendingConnections]);

  if (unreadCount === 0) return null;

  return (
    <div className="connection-requests-badge">
      <span className="badge-count">{unreadCount > 99 ? '99+' : unreadCount}</span>
      <span className="badge-label">Connection Requests</span>
    </div>
  );
}
```

## Usage with Quick Actions

```tsx theme={null}
import { useFetchReceivedPendingConnections } from "@replyke/react-js";
import { useState, useEffect } from "react";

function QuickConnectionActions() {
  const fetchReceivedPendingConnections = useFetchReceivedPendingConnections();
  const [recentRequests, setRecentRequests] = useState<any[]>([]);
  const [processing, setProcessing] = useState<Set<string>>(new Set());

  useEffect(() => {
    const loadRecentRequests = async () => {
      try {
        const result = await fetchReceivedPendingConnections({ page: 1, limit: 5 });
        setRecentRequests(result.connections);
      } catch (error) {
        console.error("Failed to load recent requests:", error);
      }
    };

    loadRecentRequests();
  }, [fetchReceivedPendingConnections]);

  const handleQuickAction = async (
    connectionId: string,
    action: 'accept' | 'decline'
  ) => {
    setProcessing(prev => new Set(prev).add(connectionId));

    try {
      if (action === 'accept') {
        // Call useAcceptConnection hook
        console.log("Quick accepting:", connectionId);
      } else {
        // Call useDeclineConnection hook
        console.log("Quick declining:", connectionId);
      }

      // Remove the request from the list
      setRecentRequests(prev => prev.filter(req => req.id !== connectionId));
    } catch (error) {
      console.error(`Failed to ${action} connection:`, error);
    } finally {
      setProcessing(prev => {
        const newSet = new Set(prev);
        newSet.delete(connectionId);
        return newSet;
      });
    }
  };

  if (recentRequests.length === 0) {
    return <div className="no-requests">No pending connection requests</div>;
  }

  return (
    <div className="quick-connection-actions">
      <h3>Recent Connection Requests</h3>

      <div className="quick-actions-list">
        {recentRequests.map(request => (
          <div key={request.id} className="quick-action-item">
            <div className="user-summary">
              <strong>{request.user.displayName || request.user.username}</strong>
              <span className="username">@{request.user.username}</span>
            </div>

            <div className="quick-buttons">
              <button
                onClick={() => handleQuickAction(request.id, 'accept')}
                disabled={processing.has(request.id)}
                className="quick-accept"
                title="Accept connection request"
              >
                {processing.has(request.id) ? '⏳' : '✓'}
              </button>
              <button
                onClick={() => handleQuickAction(request.id, 'decline')}
                disabled={processing.has(request.id)}
                className="quick-decline"
                title="Decline connection request"
              >
                {processing.has(request.id) ? '⏳' : '✗'}
              </button>
            </div>
          </div>
        ))}
      </div>

      <div className="view-all">
        <a href="/connections/requests">View all requests</a>
      </div>
    </div>
  );
}
```

## Usage with Bulk Actions

```tsx theme={null}
import { useFetchReceivedPendingConnections } from "@replyke/react-js";
import { useState, useEffect } from "react";

function BulkConnectionRequestsManager() {
  const fetchReceivedPendingConnections = useFetchReceivedPendingConnections();
  const [allRequests, setAllRequests] = useState<any[]>([]);
  const [selectedRequests, setSelectedRequests] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(false);
  const [bulkProcessing, setBulkProcessing] = useState(false);

  const loadAllRequests = async () => {
    setLoading(true);
    try {
      let allRequests: any[] = [];
      let currentPage = 1;
      let hasMore = true;

      while (hasMore) {
        const result = await fetchReceivedPendingConnections({ page: currentPage, limit: 50 });
        allRequests = [...allRequests, ...result.connections];
        hasMore = result.pagination.hasNextPage;
        currentPage++;
      }

      setAllRequests(allRequests);
    } catch (error) {
      console.error("Failed to load all requests:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAllRequests();
  }, []);

  const handleSelectRequest = (connectionId: string) => {
    const newSelected = new Set(selectedRequests);
    if (newSelected.has(connectionId)) {
      newSelected.delete(connectionId);
    } else {
      newSelected.add(connectionId);
    }
    setSelectedRequests(newSelected);
  };

  const handleSelectAll = () => {
    if (selectedRequests.size === allRequests.length) {
      setSelectedRequests(new Set());
    } else {
      setSelectedRequests(new Set(allRequests.map(req => req.id)));
    }
  };

  const handleBulkAction = async (action: 'accept' | 'decline') => {
    if (selectedRequests.size === 0) return;

    const confirmed = window.confirm(
      `Are you sure you want to ${action} ${selectedRequests.size} connection requests?`
    );
    if (!confirmed) return;

    setBulkProcessing(true);

    try {
      for (const connectionId of selectedRequests) {
        if (action === 'accept') {
          // Call useAcceptConnection hook
          console.log("Bulk accepting:", connectionId);
        } else {
          // Call useDeclineConnection hook
          console.log("Bulk declining:", connectionId);
        }

        // Brief delay between operations
        await new Promise(resolve => setTimeout(resolve, 500));
      }

      // Refresh the list after bulk action
      setSelectedRequests(new Set());
      await loadAllRequests();
    } catch (error) {
      console.error(`Failed to bulk ${action} connections:`, error);
    } finally {
      setBulkProcessing(false);
    }
  };

  return (
    <div className="bulk-requests-manager">
      <div className="header">
        <h2>Connection Requests ({allRequests.length})</h2>

        <div className="bulk-controls">
          <label className="select-all">
            <input
              type="checkbox"
              checked={selectedRequests.size === allRequests.length && allRequests.length > 0}
              onChange={handleSelectAll}
            />
            Select All
          </label>

          {selectedRequests.size > 0 && (
            <div className="bulk-actions">
              <button
                onClick={() => handleBulkAction('accept')}
                disabled={bulkProcessing}
                className="bulk-accept-btn"
              >
                Accept Selected ({selectedRequests.size})
              </button>
              <button
                onClick={() => handleBulkAction('decline')}
                disabled={bulkProcessing}
                className="bulk-decline-btn"
              >
                Decline Selected ({selectedRequests.size})
              </button>
            </div>
          )}
        </div>
      </div>

      {bulkProcessing && (
        <div className="bulk-processing">
          <p>Processing {selectedRequests.size} requests...</p>
        </div>
      )}

      {loading ? (
        <div>Loading connection requests...</div>
      ) : (
        <div className="requests-grid">
          {allRequests.map(request => (
            <div key={request.id} className="request-card">
              <label className="request-selector">
                <input
                  type="checkbox"
                  checked={selectedRequests.has(request.id)}
                  onChange={() => handleSelectRequest(request.id)}
                />
              </label>

              <div className="request-content">
                <div className="user-info">
                  <h4>{request.user.displayName || request.user.username}</h4>
                  <p>@{request.user.username}</p>
                </div>

                <div className="request-meta">
                  <small>Received: {new Date(request.createdAt).toLocaleDateString()}</small>
                  {request.message && (
                    <p className="message">"{request.message}"</p>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
```

## Parameters & Returns

### Parameters

The hook returns a function that accepts an optional object with the following fields:

<ParamField path="page" type="number">
  1
</ParamField>

<ParamField path="limit" type="number">
  20
</ParamField>

### Returns

The function returns a Promise that resolves to a `PendingConnectionListResponse` object containing:

#### `PendingConnectionListResponse`

<ResponseField name="connections" type="PendingConnection[]">
  Array of pending connection information
</ResponseField>

<ResponseField name="pagination" type="PaginationInfo">
  Pagination metadata
</ResponseField>

#### `PendingConnection`

| Field       | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| `id`        | `string`  | Unique ID of the connection request               |
| `user`      | `User`    | User object containing requester information      |
| `message`   | `string?` | Optional message sent with the connection request |
| `createdAt` | `string`  | ISO date string of when the request was received  |

#### `PaginationInfo`

| Field             | Type      | Description                                     |
| ----------------- | --------- | ----------------------------------------------- |
| `currentPage`     | `number`  | Current page number                             |
| `totalPages`      | `number`  | Total number of pages available                 |
| `totalCount`      | `number`  | Total number of received pending requests       |
| `hasNextPage`     | `boolean` | Whether there are more pages after current page |
| `hasPreviousPage` | `boolean` | Whether there are pages before current page     |
| `limit`           | `number`  | Number of items per page used in this request   |

### Error Handling

The hook will throw errors in the following cases:

* No project is specified
* No user is logged in
* Network connection issues

### Use Cases

This hook is essential for:

**Notification Systems:**

* Connection request inbox
* Real-time notification badges
* Push notification triggers

**User Engagement:**

* Dashboard widgets showing pending requests
* Quick action interfaces
* Bulk request management

**Professional Networking:**

* LinkedIn-style connection management
* Business networking platforms
* Professional community features

### Best Practices

1. **Real-time Updates**: Implement periodic polling or websocket connections for live updates
2. **Notification Badges**: Show unread count in navigation
3. **Quick Actions**: Provide fast accept/decline options
4. **Bulk Operations**: Allow bulk acceptance/decline for power users
5. **Message Display**: Show personal messages to encourage connections
6. **Empty States**: Design helpful empty states when no requests exist

### Related Hooks

* `useFetchSentPendingConnections` - Get outgoing connection requests
* `useAcceptConnection` - Accept received connection requests
* `useDeclineConnection` - Decline received connection requests
* `useConnectionManager` - Comprehensive connection state management
