import { CollectionState, Filter } from '@wix/bex-core'; import { useState, useRef } from 'react'; import { useCreateFilterCollection } from './useFilterCollection'; import { wordStartsWithMatch } from '../utils/wordStartsWithMatch'; let queryNameCounter = 0; export function useStaticListFilterCollection( /** * This is a reference to the filter that was defined in the main collection. For example: `collection.filters.` */ filter: Filter, /** * Static list of items to show in the filter component */ list: T[], ): CollectionState { // if a new list is passed, update as ref so `fetchData` can access the latest list (collection should still be re-fetched by consumer). const listRef = useRef(list); listRef.current = list; const createFilterCollection = useCreateFilterCollection(); const [queryName] = useState( () => `static-list-filter-collection-${ filter.name || '' }-${queryNameCounter++}`, ); const [collection] = useState(() => createFilterCollection(filter, { queryName, fetchData: async (query) => { const { search } = query; let filteredList = listRef.current; if (search) { const startsWith = wordStartsWithMatch(search); filteredList = listRef.current.filter((item) => { return startsWith(filter.itemName(item)); }); } return { items: filteredList, hasNext: false, }; }, queryOptions: { refetchOnMount: false, retryOnMount: false, } as {}, }), ); return collection; }