1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 04:46:40 +07:00

removed search reducer completely

This commit is contained in:
Fedor Katurov 2022-01-04 15:51:44 +07:00
parent 38eedab3c2
commit b82ccfb786
22 changed files with 146 additions and 570 deletions

View file

@ -1,24 +1,69 @@
import { useCallback } from 'react';
import { flowChangeSearch, flowLoadMoreSearch } from '~/redux/flow/actions';
import { useDispatch } from 'react-redux';
import { useShallowSelect } from '~/hooks/data/useShallowSelect';
import { selectFlow } from '~/redux/flow/selectors';
import { useCallback, useEffect, useState } from 'react';
import useSWRInfinite from 'swr/infinite';
import { flatten } from 'ramda';
import { getSearchResults } from '~/redux/flow/api';
import { KeyLoader } from 'swr';
import { INode } from '~/redux/types';
import { GetSearchResultsRequest } from '~/redux/flow/types';
import { COMMENTS_DISPLAY } from '~/constants/node';
const RESULTS_COUNT = 20;
const getKey: (text: string) => KeyLoader<INode[]> = text => (pageIndex, previousPageData) => {
if ((pageIndex > 0 && !previousPageData?.length) || !text) return null;
const props: GetSearchResultsRequest = {
text,
skip: pageIndex * RESULTS_COUNT,
take: RESULTS_COUNT,
};
return JSON.stringify(props);
};
export const useSearch = () => {
const dispatch = useDispatch();
const { search } = useShallowSelect(selectFlow);
const [searchText, setSearchText] = useState('');
const [debouncedSearchText, setDebouncedSearchText] = useState('');
const onSearchLoadMore = useCallback(() => {
if (search.is_loading_more) return;
dispatch(flowLoadMoreSearch());
}, [search.is_loading_more, dispatch]);
const { data, size, setSize, mutate, isValidating } = useSWRInfinite(
getKey(debouncedSearchText),
async (key: string) => {
const props: GetSearchResultsRequest = key && JSON.parse(key);
const onSearchChange = useCallback(
(text: string) => {
dispatch(flowChangeSearch({ text }));
},
[dispatch]
if (!props) {
return [] as INode[];
}
const result = await getSearchResults(props);
return result.nodes;
}
);
return { onSearchChange, onSearchLoadMore, search };
const loadMore = useCallback(() => setSize(size + 1), [setSize, size]);
const hasMore = (data?.[size - 1]?.length || 0) >= RESULTS_COUNT;
const results = flatten(data || []);
useEffect(() => {
const timeout = setTimeout(async () => {
setDebouncedSearchText(searchText.length > 2 ? searchText : '');
await setSize(0);
await mutate([]);
}, 300);
return () => clearTimeout(timeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchText]);
console.log({ hasMore, data });
return {
results,
searchText,
setSearchText,
hasMore,
loadMore,
isLoading: isValidating,
};
};