@aws-northstar/ui
Version:
NorthStar Design System v2
51 lines (47 loc) • 2.58 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
/** *******************************************************************************************************************
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. *
******************************************************************************************************************** */
import Select from '@cloudscape-design/components/select';
import { useCallback, useMemo } from 'react';
/**
* Extends the Cloudscape Select component with pagination options for @tanstack/react-query infinite query hooks.
* Compatible with generated hooks for paginated operations from <a href='https://aws.github.io/aws-pdk/developer_guides/type-safe-api/index.html' target='_blank' rel='noreferrer noopener'>AWS PDK Type Safe API</a>.
*/
const InfiniteQuerySelect = ({ query, itemsKey, toOption, extendData, ...props }) => {
const allLocalData = useMemo(() => {
const flattenedData = (query?.data?.pages ?? []).flatMap((p) => p[itemsKey]);
return extendData ? extendData(flattenedData) : flattenedData;
}, [query.data?.pages, extendData, itemsKey]);
const options = useMemo(() => {
return allLocalData.map(toOption);
}, [allLocalData, toOption]);
const onLoadItems = useCallback(async ({ detail: { firstPage, samePage } }) => {
if (firstPage) {
await query.refetch();
}
if (!samePage) {
await query.fetchNextPage();
}
}, [query]);
const status = useMemo(() => {
if (query.isLoading || query.isFetchingNextPage) {
return 'loading';
}
else if (query.hasNextPage) {
return 'pending';
}
return 'finished';
}, [query.isLoading, query.hasNextPage, query.isFetchingNextPage]);
return _jsx(Select, { options: options, onLoadItems: onLoadItems, statusType: status, ...props });
};
export default InfiniteQuerySelect;