# useCollection

**Category:** Common/Hooks

## API

### Overview

The base React hook for creating a [`CollectionState`](./?path=/story/common-state--collectionstate). All other collection hooks (`useTableCollection`, `useGridCollection`, etc.) build on top of `useCollection`.

Use this hook directly when you need a collection state that is not tied to a specific component, or when building custom collection components.

```tsx
import { useCollection } from '@wix/patterns';
```

### Example

```tsx
import { useCollection } from '@wix/patterns';

const collection = useCollection({
  queryName: 'my-items',
  fetchData: async (query) => {
    const { items, total } = await api.list(query);
    return { items, total };
  },
  itemKey: (item) => item.id,
  limit: 50,
  filters: { status: stringFilter() },
});

// collection.keyedItems, collection.total, collection.invalidate(), etc.
```

### Returns

[CollectionState](./?path=/story/common-state--collectionstate)

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `paginationMode` | `"cursor" \| "offset"` | No | `offset` | Pagination type supported by `fetchData`. <br> <br> Supported values: <br> - `"offset"`: Server accepts `query.offset`. <br> - `"cursor"`: Server returns a cursor when `fetchData` is called. |
| `fetchData` | `(query: ComputedQuery<F>) => Promise<DataResultRaw<T>>` | Yes | - | Function that fetches the collection data.<br> <br> Supported parameters: <br> - `query`: [object] [ComputedQuery](./com?path=/story/common-models--computedquery) instance. <br> <br> Must return a [DataResultRaw](./?path=/story/common-models--dataresultraw) Promise. |
| `fetchTotal` | `FetchTotalFn` | No | - | A function that fetches the total number of items in the collection.<br> <br> Supported parameters: <br> - `query`: [object] [ComputedQuery](./com?path=/story/common-models--computedquery) of type `CursorQuery`. <br> <br> Must return a number Promise. |
| `filters` | `FiltersMap` | Yes | - | Defines the filters that the collection supports. <br> <br> Either an [arrayFilter](./?path=/story/features-filter-factories--arrayfilter) or a [customFilter](./?path=/story/features-filter-factories--customfilter). |
| `itemName` | `(item: T) => string` | Yes | - | Used to identify the item in many messages from Wix Patterns. <br> <br> For example, '{entity} "{itemName}" was deleted successfully' may become 'Contact "Johnny Doe" was deleted successfully'. <br> <br> If your data has an ID, then `itemKey` will default to this ID. |
| `itemKey` | `(item: T) => string` | Yes | - | Unique key within the collection. The item's ID is often used for its key. <br> <br> If your data has an ID, then `itemKey` will default to this ID. |
| `limit` | `number` | No | - | Maximum number of items fetched per page. |
| `disableAutoSelectAllCount` | `boolean` | No | - | Whether to disable "Select All" server simulation for bulk selection. |
| `useNewSelectAllLogic` | `boolean` | No | - | Whether to enable new "Select All" logic. <br> <br> If `true`: <br> - Unchecking items after checking "Select All" does not fallback to specific selection logic and values. This means in `<bulkActionToolbar />` and `<MultiBulkActionToolbar />`, "Total Selected" will show `total - unchecked items` and `isSelectAll` will be true. <br> - You will receive a list of unchecked IDs. |
| `queryName` | `string` | Yes | - | Unique value for each API endpoint consumed in `fetchData`. |
| `fqdn` | `string` | No | - | Entity fqdn. |
| `toExtendedFields` | `((item: T) => ExtendedFields \| null)` | No | - | The `ExtendedFields` object used to render custom field values Optional in case your data complies to the type `{ extendedFields: ExtendedFields }` |
| `fetchErrorMessage` | `((params: { err: unknown; isOnline: boolean; }) => string \| null)` | No | - | Message shown in a toast when fetching from the server fails. <br> <br> If the function returns a nullish value, no toast is shown. @deprecated Instead of using `fetchErrorMessage`, use `errorState` prop in the component, which will show the error message in the card. |
| `persistQueryToUrl` | `boolean` | No | `false` | Persist the selected filters, search & sort in the query parameters of the URL.<br/> For improved readability, sort & columns are formatted in CSV-like formatting, i.e "?sort=name+desc,price+asc". Do not use commas and/or spaces for your columns IDs.<br> Note: The filters from the selected view will be persist, but the actual view will not be selected |
| `refreshOnColumnsChange` | `boolean` | No | `false` | Whether the collection refreshes when different columns are selected. <br> <br> Selected columns are passed in `fetchData(query.columns)`. |
| `selectionConsistencyMode` | `"clear" \| "preserve"` | No | `preserve` | Preserve or clear selection after applying a new search or filter. |
| `events` | `CollectionEvents<F>` | No | - | Optional callbacks for various events of the collection state lifecycle - `onInitialPageFetched` - when the first page of items is ready - `onSearch` - when fetching new items as a result new search - `onSearchResults` - when the result of a search is ready - `onNewPageStart` - when starting to load the next page of items - `onNewPageAdded` - when the result of the next page is ready - `onError` - When `fetchData` throws an error. Return `true` from this function if the error was reported and shouldn't be reported again internally. |

