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

# ページネーション

> UserPaginator と汎用のページネータユーティリティを使い、手動の fetchNext ループや非同期イテレーションで、任意のリストエンドポイントの X API レスポンスを TypeScript でページ処理します。

SDK は、ページネーションレスポンスを返す任意のエンドポイントと組み合わせて使える汎用のページネータユーティリティを提供します。メソッドは通常のレスポンスを返し、それをページネータでラップします。

### 基本的なページネーション

<CodeGroup dropdown>
  ```typescript title="quick-start.ts" lines wrap icon="square-js" theme={null} theme={null}
  import { Client, UserPaginator, PaginatedResponse, Schemas } from '@xdevplatform/xdk';

  const client: Client = new Client({ bearerToken: 'your-bearer-token' });

  // Wrap any list endpoint with proper typing
  const followers: UserPaginator = new UserPaginator(
    async (token?: string): Promise<PaginatedResponse<Schemas.User>> => {
      const res = await client.users.getFollowers('<userId>', {
        maxResults: 100,
        paginationToken: token,
        userFields: ['id','name','username'],
      });
      return { 
        data: res.data ?? [], 
        meta: res.meta, 
        includes: res.includes, 
        errors: res.errors 
      };
    }
  );
  ```

  ```javascript title="quick-start.js" lines wrap icon="square-js" theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';
  import { UserPaginator } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: 'your-bearer-token' });

  const followers = new UserPaginator(async (token) => {
    const res = await client.users.getFollowers('<userId>', {
      maxResults: 100,
      paginationToken: token,
      userFields: ['id','name','username'],
    });
    return { data: res.data ?? [], meta: res.meta, includes: res.includes, errors: res.errors };
  });
  ```
</CodeGroup>

### 手動でのページング

<CodeGroup>
  ```typescript manual.ts theme={null} theme={null}
  import { UserPaginator, Schemas } from '@xdevplatform/xdk';

  await followers.fetchNext();          // first page
  while (!followers.done) {
    await followers.fetchNext();        // subsequent pages
  }

  const userCount: number = followers.users.length;  // all fetched users
  const firstUser: Schemas.User | undefined = followers.users[0];
  const nextToken: string | undefined = followers.meta?.nextToken;
  ```

  ```javascript manual.js theme={null} theme={null}
  await followers.fetchNext();
  while (!followers.done) await followers.fetchNext();
  console.log(followers.items.length);
  ```
</CodeGroup>

### 非同期イテレーション

<CodeGroup>
  ```typescript async.ts theme={null} theme={null}
  import { Schemas } from '@xdevplatform/xdk';

  for await (const user of followers) {
    const typedUser: Schemas.User = user;
    console.log(typedUser.username);  // fully typed access
  }
  ```

  ```javascript async.js theme={null} theme={null}
  for await (const user of followers) {
    console.log(user.username);
  }
  ```
</CodeGroup>

### 次のページを新しいインスタンスとして取得

<CodeGroup>
  ```typescript next.ts theme={null} theme={null}
  import { UserPaginator } from '@xdevplatform/xdk';

  await followers.fetchNext();
  if (!followers.done) {
    const page2: UserPaginator = await followers.next(); // independent paginator starting at next page
    await page2.fetchNext();
    console.log(page2.users.length);  // items from second page
  }
  ```

  ```javascript next.js theme={null} theme={null}
  await followers.fetchNext();
  if (!followers.done) {
    const page2 = await followers.next();
    await page2.fetchNext();
  }
  ```
</CodeGroup>

### エラーハンドリングとレート制限

<CodeGroup>
  ```typescript title="errors.ts" lines wrap icon="square-js" theme={null} theme={null}
  import { UserPaginator, Schemas } from '@xdevplatform/xdk';

  try {
    for await (const item of followers) {
      const user: Schemas.User = item;
      // process user...
    }
  } catch (err: unknown) {
    if (followers.rateLimited) {
      console.error('Rate limited, backoff required');
      // backoff / retry later
    } else {
      console.error('Pagination error:', err);
      throw err;
    }
  }
  ```

  ```javascript errors.js theme={null} theme={null}
  try {
    for await (const item of followers) {
      // ...
    }
  } catch (err) {
    if (followers.rateLimited) {
      // backoff / retry later
    } else {
      throw err;
    }
  }
  ```
</CodeGroup>

<Info>
  JavaScript/TypeScript XDK を使った詳細なコードサンプルは、[コードサンプル GitHub リポジトリ](https://github.com/xdevplatform/samples/tree/main/javascript)を参照してください。
</Info>
