useSearch.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { useCallback, useEffect } from 'react';
  2. import { useDebounce } from 'react-use';
  3. import { backendSrv } from 'app/core/services/backend_srv';
  4. import { SearchSrv } from 'app/core/services/search_srv';
  5. import { FETCH_RESULTS, FETCH_ITEMS, TOGGLE_SECTION, SEARCH_START, FETCH_ITEMS_START } from '../reducers/actionTypes';
  6. import { DashboardSection, UseSearch } from '../types';
  7. import { hasId, getParsedQuery } from '../utils';
  8. const searchSrv = new SearchSrv();
  9. /**
  10. * Base hook for search functionality.
  11. * Returns state and dispatch, among others, from 'reducer' param, so it can be
  12. * further extended.
  13. * @param query
  14. * @param reducer - return result of useReducer
  15. * @param params - custom params
  16. */
  17. export const useSearch: UseSearch = (query, reducer, params = {}) => {
  18. const { queryParsing } = params;
  19. const [state, dispatch] = reducer;
  20. const search = () => {
  21. dispatch({ type: SEARCH_START });
  22. const parsedQuery = getParsedQuery(query, queryParsing);
  23. searchSrv.search(parsedQuery).then((results) => {
  24. dispatch({ type: FETCH_RESULTS, payload: results });
  25. });
  26. };
  27. // Set loading state before debounced search
  28. useEffect(() => {
  29. dispatch({ type: SEARCH_START });
  30. }, [query.tag, query.sort, query.starred, query.layout, dispatch]);
  31. useDebounce(search, 300, [query, queryParsing]);
  32. const onToggleSection = useCallback(
  33. (section: DashboardSection) => {
  34. if (hasId(section.title) && !section.items.length) {
  35. dispatch({ type: FETCH_ITEMS_START, payload: section.id });
  36. backendSrv.search({ folderIds: [section.id] }).then((items) => {
  37. dispatch({ type: FETCH_ITEMS, payload: { section, items } });
  38. dispatch({ type: TOGGLE_SECTION, payload: section });
  39. });
  40. } else {
  41. dispatch({ type: TOGGLE_SECTION, payload: section });
  42. }
  43. },
  44. [dispatch]
  45. );
  46. return { state, dispatch, onToggleSection };
  47. };