useAsyncList
Manages state for an immutable async loaded list data structure, and provides convenience methods to update the data over time. Manages loading and error states, pagination, and sorting.
| install | yarn add @react-stately/data |
|---|---|
| version | 3.0.0 |
| usage | import {useAsyncList} from '@react-stately/data' |
Introduction#
useAsyncList extends on useListData, adding support for async loading, pagination, and sorting.
It manages loading and error states, supports abortable requests, and works with any data fetching library or the built-in
browser fetch API.
API#
useAsyncList<T, C = string>(
(options: AsyncListOptions<T, C>
)): AsyncListData<T>Options#
| Name | Type | Description |
load | AsyncListLoadFunction<T, C> | A function that loads the data for the items in the list. |
initialSelectedKeys | Iterable<Key> | The keys for the initially selected items. |
initialSortDescriptor | SortDescriptor | The initial sort descriptor. |
getKey | (
(item: T
)) => Key | A function that returns a unique key for an item object. |
sort | AsyncListLoadFunction<T, C> | An optional function that performs sorting. If not provided,
then sortDescriptor is passed to the load function. |
Interface#
Properties
| Name | Type | Description |
isLoading | boolean | Whether data is currently being loaded. |
items | T[] | The items in the list. |
selectedKeys | Selection | The keys of the currently selected items in the list. |
error | Error | If loading data failed, then this contains the error that occurred. |
sortDescriptor | SortDescriptor | The current sort descriptor for the list. |
Methods
| Method | Description |
reload(): void | Reloads the data in the list. |
loadMore(): void | Loads the next page of data in the list. |
sort(
(descriptor: SortDescriptor
)): void | Triggers sorting for the list. |
setSelectedKeys(
(keys: Selection
)): void | Sets the selected keys. |
getItem(
(key: Key
)): T | Gets an item from the list by key. |
insert(
(index: number,
, ...values: T[]
)): void | Inserts items into the list at the given index. |
insertBefore(
(key: Key,
, ...values: T[]
)): void | Inserts items into the list before the item at the given key. |
insertAfter(
(key: Key,
, ...values: T[]
)): void | Inserts items into the list after the item at the given key. |
append(
(...values: T[]
)): void | Appends items to the list. |
prepend(
(...values: T[]
)): void | Prepends items to the list. |
remove(
(...keys: Key[]
)): void | Removes items from the list by their keys. |
removeSelectedItems(): void | Removes all items from the list that are currently in the set of selected items. |
move(
(key: Key,
, toIndex: number
)): void | Moves an item within the list. |
update(
(key: Key,
, newValue: T
)): void | Updates an item in the list. |
Example#
To construct an async list, pass a load function to useAsyncList that returns the items to render.
You can use the state returned by useAsyncList to render a collection component.
This example fetches a list of Pokemon from an API and displays them in a Picker. It uses
fetch to load the data, passing through the abort signal
given by useAsyncList and returning the results from the API. The isLoading prop is passed to the Picker
to tell it to render the loading spinner while data is loading.
let list = useAsyncList({
async load({signal}) {
let res = await fetch('https://pokeapi.co/api/v2/pokemon' {signal});
let json = await resjson();
return {items: jsonresults};
}
});
<Picker label="Pick a Pokemon" items=listitems isLoading=listisLoading>
(item) => <Item key=itemname>itemname</Item>
</Picker>let list = useAsyncList({
async load({signal}) {
let res = await fetch(
'https://pokeapi.co/api/v2/pokemon'
{signal}
);
let json = await resjson();
return {items: jsonresults};
}
});
<Picker
label="Pick a Pokemon"
items=listitems
isLoading=listisLoading>
(item) => <Item key=itemname>itemname</Item>
</Picker>let list = useAsyncList({
async load({signal}) {
let res = await fetch(
'https://pokeapi.co/api/v2/pokemon'
{signal}
);
let json = await resjson();
return {
items: jsonresults
};
}
});
<Picker
label="Pick a Pokemon"
items=listitems
isLoading=
listisLoading
>
(item) => (
<Item
key=itemname>
itemname
</Item>
)
</Picker>Infinite loading#
useAsyncList also supports paginated data, which is common in many APIs to avoid loading too many items at once.
This is accomplished by returning a cursor in addition to items from the load function. When the loadMore method
is called, the cursor is passed back to your load function, which you can use to determine the URL for the next
page. The onLoadMore prop supported by many collection components notifies you when you should load more data
as the user scrolls.
This example expands on the previous one to support infinite scrolling through all known Pokemon. It returns the
next property from the API response as the cursor, and uses it instead of the original API URL for subsequent
page loads. It passes the onLoadMore prop to Picker, which triggers loading more items as the user scrolls down.
let list = useAsyncList({
async load({signal cursor}) {
// If no cursor is available, then we're loading the first page.
// Otherwise, the cursor is the next URL to load, as returned from the previous page.
let res = await fetch(cursor || 'https://pokeapi.co/api/v2/pokemon' {
signal
});
let json = await resjson();
return {
items: jsonresults
cursor: jsonnext
};
}
});
<Picker
label="Pick a Pokemon"
items=listitems
isLoading=listisLoading
onLoadMore=listloadMore>
(item) => <Item key=itemname>itemname</Item>
</Picker>let list = useAsyncList({
async load({signal cursor}) {
// If no cursor is available, then we're loading the first page.
// Otherwise, the cursor is the next URL to load, as returned from the previous page.
let res = await fetch(
cursor || 'https://pokeapi.co/api/v2/pokemon'
{signal}
);
let json = await resjson();
return {
items: jsonresults
cursor: jsonnext
};
}
});
<Picker
label="Pick a Pokemon"
items=listitems
isLoading=listisLoading
onLoadMore=listloadMore>
(item) => <Item key=itemname>itemname</Item>
</Picker>let list = useAsyncList({
async load({
signal
cursor
}) {
// If no cursor is available, then we're loading the first page.
// Otherwise, the cursor is the next URL to load, as returned from the previous page.
let res = await fetch(
cursor ||
'https://pokeapi.co/api/v2/pokemon'
{signal}
);
let json = await resjson();
return {
items:
jsonresults
cursor: jsonnext
};
}
});
<Picker
label="Pick a Pokemon"
items=listitems
isLoading=
listisLoading
onLoadMore=
listloadMore
>
(item) => (
<Item
key=itemname>
itemname
</Item>
)
</Picker>Reloading data#
Data can be reloaded by calling the reload method of the list.
listreload();
listreload();
listreload();
Sorting#
Some components like tables support sorting data. You may also have custom UI to implement this in other components.
This can be implemented by passing a sort function to useAsyncList, or by using the sortDescriptor passed to
load if no sort function is given. Passing a separate sort function could be useful when implementing client side
sorting. Using the sortDescriptor in load is useful when you need to implement server side sorting, which might be
an API parameter.
Client side sorting#
This example shows how to implement client side sorting by passing a sort function to useAsyncList and sorting the
items array.
let list = useAsyncList({
async load({signal}) {
// Same load function as before
}
sort({items sortDescriptor}) {
return {
items: itemssort((a b) => {
// Compare the items by the sorted column
let cmp = a[sortDescriptorcolumn] < b[sortDescriptorcolumn] ? -1 : 1;
// Flip the direction if descending order is specified.
if (sortDescriptordirection === 'descending') {
cmp *= -1;
}
return cmp;
})
};
}
});
let list = useAsyncList({
async load({signal}) {
// Same load function as before
}
sort({items sortDescriptor}) {
return {
items: itemssort((a b) => {
// Compare the items by the sorted column
let cmp =
a[sortDescriptorcolumn] <
b[sortDescriptorcolumn]
? -1
: 1;
// Flip the direction if descending order is specified.
if (sortDescriptordirection === 'descending') {
cmp *= -1;
}
return cmp;
})
};
}
});
let list = useAsyncList({
async load({signal}) {
// Same load function as before
}
sort({
items
sortDescriptor
}) {
return {
items: itemssort(
(a b) => {
// Compare the items by the sorted column
let cmp =
a[
sortDescriptor
column
] <
b[
sortDescriptor
column
]
? -1
: 1;
// Flip the direction if descending order is specified.
if (
sortDescriptordirection ===
'descending'
) {
cmp *= -1;
}
return cmp;
}
)
};
}
});
Server side sorting#
Server side sorting could be implemented by using the sortDescriptor in the load function, and passing a
parameter to the API.
let list = useAsyncList({
async load({signal sortDescriptor}) {
let url = new URL('http://example.com/api');
if (sortDescriptor) {
urlsearchParamsappend('sort_key' sortDescriptorcolumn);
urlsearchParamsappend('sort_direction' sortDescriptordirection);
}
let res = await fetch(url {signal});
let json = await resjson();
return {
items: jsonresults
};
}
});
let list = useAsyncList({
async load({signal sortDescriptor}) {
let url = new URL('http://example.com/api');
if (sortDescriptor) {
urlsearchParamsappend(
'sort_key'
sortDescriptorcolumn
);
urlsearchParamsappend(
'sort_direction'
sortDescriptordirection
);
}
let res = await fetch(url {signal});
let json = await resjson();
return {
items: jsonresults
};
}
});
let list = useAsyncList({
async load({
signal
sortDescriptor
}) {
let url = new URL(
'http://example.com/api'
);
if (sortDescriptor) {
urlsearchParamsappend(
'sort_key'
sortDescriptorcolumn
);
urlsearchParamsappend(
'sort_direction'
sortDescriptordirection
);
}
let res = await fetch(
url
{
signal
}
);
let json = await resjson();
return {
items: jsonresults
};
}
});
Pre-selecting items#
useAsyncList manages selection state for the list in addition to its data. If you need to programmatically select items
during the initial load, you can do so using the initialSelectedKeys option or by returning selectedKeys from the
load function in addition to items.
Selecting before loading#
If you know what keys to select before items are loaded from the server, use the initialSelectedKeys option.
let list = useAsyncList({
initialSelectedKeys: ['foo' 'bar']
async load({signal}) {
// Same load function as before
}
});
let list = useAsyncList({
initialSelectedKeys: ['foo' 'bar']
async load({signal}) {
// Same load function as before
}
});
let list = useAsyncList({
initialSelectedKeys: [
'foo'
'bar'
]
async load({signal}) {
// Same load function as before
}
});
Selecting based on loaded data#
If you need to compute which keys to select based on the loaded data, return selectedKeys from the load function
in addition to the items.
let list = useAsyncList({
async load({signal}) {
let res = await fetch('http://example.com/api' {signal});
let json = await resjson();
// Return items and compute selectedKeys based on the data and return a list of ids.
return {
items: jsonresults
selectedKeys: jsonresults
filter((item) => itemisSelected)
map((item) => itemid)
};
}
});
let list = useAsyncList({
async load({signal}) {
let res = await fetch('http://example.com/api' {
signal
});
let json = await resjson();
// Return items and compute selectedKeys based on the data and return a list of ids.
return {
items: jsonresults
selectedKeys: jsonresults
filter((item) => itemisSelected)
map((item) => itemid)
};
}
});
let list = useAsyncList({
async load({signal}) {
let res = await fetch(
'http://example.com/api'
{signal}
);
let json = await resjson();
// Return items and compute selectedKeys based on the data and return a list of ids.
return {
items:
jsonresults
selectedKeys: jsonresults
filter(
(item) =>
itemisSelected
)
map(
(item) =>
itemid
)
};
}
});
Client side updates#
All client side updating methods supported by useListData are also supported by useAsyncList.
See the docs for useListData for more details.
| Name | Type | Description |
load | AsyncListLoadFunction<T, C> | A function that loads the data for the items in the list. |
initialSelectedKeys | Iterable<Key> | The keys for the initially selected items. |
initialSortDescriptor | SortDescriptor | The initial sort descriptor. |
getKey | (
(item: T
)) => Key | A function that returns a unique key for an item object. |
sort | AsyncListLoadFunction<T, C> | An optional function that performs sorting. If not provided,
then sortDescriptor is passed to the load function. |
(
(state: AsyncListLoadOptions<T, C>
)) => Promise<AsyncListStateUpdate<T, C>>| Name | Type | Description |
items | T[] | The items currently in the list. |
selectedKeys | Selection | The keys of the currently selected items in the list. |
sortDescriptor | SortDescriptor | The current sort descriptor for the list. |
signal | AbortSignal | An abort signal used to notify the load function that the request has been aborted. |
cursor | C | The pagination cursor returned from the last page load. |
| Name | Type | Description |
items | Iterable<T> | The new items to append to the list. |
selectedKeys | Iterable<Key> | The keys to add to the selection. |
sortDescriptor | SortDescriptor | The sort descriptor to set. |
cursor | C | The pagination cursor to be used for the next page load. |
Properties
| Name | Type | Description |
isLoading | boolean | Whether data is currently being loaded. |
items | T[] | The items in the list. |
selectedKeys | Selection | The keys of the currently selected items in the list. |
error | Error | If loading data failed, then this contains the error that occurred. |
sortDescriptor | SortDescriptor | The current sort descriptor for the list. |
Methods
| Method | Description |
reload(): void | Reloads the data in the list. |
loadMore(): void | Loads the next page of data in the list. |
sort(
(descriptor: SortDescriptor
)): void | Triggers sorting for the list. |
setSelectedKeys(
(keys: Selection
)): void | Sets the selected keys. |
getItem(
(key: Key
)): T | Gets an item from the list by key. |
insert(
(index: number,
, ...values: T[]
)): void | Inserts items into the list at the given index. |
insertBefore(
(key: Key,
, ...values: T[]
)): void | Inserts items into the list before the item at the given key. |
insertAfter(
(key: Key,
, ...values: T[]
)): void | Inserts items into the list after the item at the given key. |
append(
(...values: T[]
)): void | Appends items to the list. |
prepend(
(...values: T[]
)): void | Prepends items to the list. |
remove(
(...keys: Key[]
)): void | Removes items from the list by their keys. |
removeSelectedItems(): void | Removes all items from the list that are currently in the set of selected items. |
move(
(key: Key,
, toIndex: number
)): void | Moves an item within the list. |
update(
(key: Key,
, newValue: T
)): void | Updates an item in the list. |