You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useSearch.js 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { useEffect, useState } from "react";
  2. import { useDispatch, useSelector } from "react-redux";
  3. import { setSearchString } from "../../store/actions/filters/filtersActions";
  4. import { selectSearchString } from "../../store/selectors/filtersSelectors";
  5. const useSearch = (applyAllFilters) => {
  6. const [searchStringLocally, setSearchStringLocally] = useState("");
  7. const [isInitallyLoaded, setIsInitiallyLoaded] = useState(false);
  8. const dispatch = useDispatch();
  9. const searchString = useSelector(selectSearchString);
  10. // On every global change of search string, new request to backend should be sent
  11. useEffect(() => {
  12. if (searchStringLocally !== searchString && applyAllFilters) {
  13. setSearchStringLocally(searchString);
  14. }
  15. if (isInitallyLoaded) {
  16. if (applyAllFilters) applyAllFilters();
  17. }
  18. }, [searchString]);
  19. // On every local change of search string, global state of search string should be also updated
  20. useEffect(() => {
  21. if (isInitallyLoaded && applyAllFilters) {
  22. dispatch(setSearchString(searchStringLocally));
  23. }
  24. }, [searchStringLocally]);
  25. const searchOffers = (searchValue) => {
  26. setIsInitiallyLoaded(true);
  27. setSearchStringLocally(searchValue);
  28. };
  29. const clear = () => {
  30. setSearchStringLocally("");
  31. };
  32. return {
  33. searchOffers,
  34. setSearchStringLocally,
  35. searchStringLocally,
  36. searchString,
  37. clear,
  38. };
  39. };
  40. export default useSearch;