| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import { useEffect, useState } from "react";
- import { useDispatch, useSelector } from "react-redux";
- import { setSearchString } from "../../store/actions/filters/filtersActions";
- import { selectSearchString } from "../../store/selectors/filtersSelectors";
-
- const useSearch = (applyAllFilters) => {
- const [searchStringLocally, setSearchStringLocally] = useState("");
- const [isInitallyLoaded, setIsInitiallyLoaded] = useState(false);
- const dispatch = useDispatch();
- const searchString = useSelector(selectSearchString);
-
- // On every global change of search string, new request to backend should be sent
- useEffect(() => {
- if (searchStringLocally !== searchString && applyAllFilters) {
- setSearchStringLocally(searchString);
- }
- if (isInitallyLoaded) {
- if (applyAllFilters) applyAllFilters();
- }
- }, [searchString]);
-
- // On every local change of search string, global state of search string should be also updated
- useEffect(() => {
- if (isInitallyLoaded && applyAllFilters) {
- dispatch(setSearchString(searchStringLocally));
- }
- }, [searchStringLocally]);
-
- const searchOffers = (searchValue) => {
- setIsInitiallyLoaded(true);
- setSearchStringLocally(searchValue);
- };
-
- const clear = () => {
- setSearchStringLocally("");
- };
-
- return {
- searchOffers,
- setSearchStringLocally,
- searchStringLocally,
- searchString,
- clear,
- };
- };
- export default useSearch;
|