Skip to content

Commit

Permalink
refactor: 불필요한 요청 보내지 않도록 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
feb-dain committed Nov 16, 2023
1 parent 4c2c861 commit 2bbeb67
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 38 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';

import { useSearchStations } from '@hooks/tanstack-query/useSearchStations';

import FlexBox from '@common/FlexBox';
import Loader from '@common/Loader';

Expand All @@ -17,15 +15,11 @@ const StationSearchBar = () => {
handleCloseResult,
showStationDetails,
isFocused,
debouncedSearchWord,
} = useStationSearchWindow();

const {
data: searchResult,
searchResult,
isLoading,
isError,
isFetching,
} = useSearchStations(debouncedSearchWord);
} = useStationSearchWindow();

return (
<StyledContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { googleMapActions } from '@stores/google-maps/googleMapStore';
import { markerInstanceStore } from '@stores/google-maps/markerInstanceStore';

import { useStationInfoWindow } from '@hooks/google-maps/useStationInfoWindow';
import { fetchSearchedStations } from '@hooks/tanstack-query/useSearchStations';
import type { SearchedStationResponse } from '@hooks/tanstack-query/useSearchStations';
import { fetchSearchedStations, useSearchStations } from '@hooks/tanstack-query/useSearchStations';
import { useDebounce } from '@hooks/useDebounce';
import useMediaQueries from '@hooks/useMediaQueries';

Expand All @@ -33,6 +34,8 @@ export const useStationSearchWindow = () => {

const [searchWord, setSearchWord] = useState('');
const [debouncedSearchWord, setDebouncedSearchWord] = useState(searchWord);
const [userSearchWord, setUserSearchWord] = useState('');
const [isSubmitted, setIsSubmitted] = useState(false);

const { openLastPanel } = useNavigationBar();
const { openStationInfoWindow } = useStationInfoWindow();
Expand All @@ -43,9 +46,17 @@ export const useStationSearchWindow = () => {
setDebouncedSearchWord(searchWord);
},
[searchWord],
400
400,
isSubmitted
);

const {
data: searchResult,
isLoading,
isError,
isFetching,
} = useSearchStations(debouncedSearchWord);

const handleOpenResult = (
event?: MouseEvent<HTMLInputElement> | FocusEvent<HTMLInputElement>
) => {
Expand All @@ -60,31 +71,6 @@ export const useStationSearchWindow = () => {
setIsFocused(false);
};

const handleSubmitSearchWord = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();

const searchWordFromForm = new FormData(event.currentTarget).get('station-search');

if (encodeURIComponent(String(searchWordFromForm)) === searchWord) {
handleOpenResult();

return;
}

handleCloseResult();

const searchedStations = await fetchSearchedStations(searchWord);
const isSearchedStationExisting =
searchedStations !== undefined && searchedStations.stations.length > 0;

if (isSearchedStationExisting) {
const [{ stationId, latitude, longitude }] = searchedStations.stations;
showStationDetails({ stationId, latitude, longitude });
}

queryClient.invalidateQueries({ queryKey: [QUERY_KEY_SEARCHED_STATION] });
};

const showStationDetails = async ({ stationId, latitude, longitude }: StationPosition) => {
googleMapActions.moveTo({ lat: latitude, lng: longitude });

Expand Down Expand Up @@ -122,9 +108,47 @@ export const useStationSearchWindow = () => {
}
};

const showStationDetailsIfFound = (searchedStations: SearchedStationResponse) => {
const isSearchedStationExisting = searchedStations?.stations.length > 0;

if (isSearchedStationExisting) {
const [{ stationId, latitude, longitude }] = searchedStations.stations;
showStationDetails({ stationId, latitude, longitude });
handleCloseResult();

queryClient.invalidateQueries({ queryKey: [QUERY_KEY_SEARCHED_STATION] });
}
};

const handleSubmitSearchWord = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
handleCloseResult();
setIsSubmitted(true);

const searchWordFromForm = new FormData(event.currentTarget).get('station-search');
const encodedSearchWord = encodeURIComponent(String(searchWordFromForm));
const isSameAsPreviousSearchWord = encodedSearchWord === userSearchWord;

if (isSameAsPreviousSearchWord) {
return;
}

setUserSearchWord(encodedSearchWord);

if (searchWord === debouncedSearchWord) {
showStationDetailsIfFound(searchResult);

return;
}

const searchedStations = await fetchSearchedStations(encodedSearchWord);
showStationDetailsIfFound(searchedStations);
};

const handleChangeSearchWord = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
const searchWord = encodeURIComponent(value);

setIsSubmitted(false);
handleOpenResult();
setSearchWord(searchWord);
};
Expand All @@ -137,5 +161,9 @@ export const useStationSearchWindow = () => {
showStationDetails,
isFocused,
debouncedSearchWord,
searchResult,
isLoading,
isError,
isFetching,
};
};
2 changes: 1 addition & 1 deletion frontend/src/hooks/tanstack-query/useSearchStations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SEARCH_SCOPE } from '@constants/stationSearch';

import type { SearchedCity, SearchedStation } from '@type/stations';

interface SearchedStationResponse {
export interface SearchedStationResponse {
stations: SearchedStation[];
cities: SearchedCity[];
}
Expand Down
13 changes: 11 additions & 2 deletions frontend/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { useEffect, useCallback } from 'react';

export const useDebounce = <T>(func: (param: T) => void, dependencies: string[], delay: number) => {
export const useDebounce = <T>(
func: (param: T) => void,
dependencies: string[],
delay: number,
shouldClear?: boolean
) => {
const callback = useCallback(func, dependencies);

useEffect(() => {
const timeout = setTimeout(callback, delay);

if (shouldClear) {
clearTimeout(timeout);
}

return () => clearTimeout(timeout);
}, [callback, delay]);
}, [callback, delay, shouldClear]);
};

0 comments on commit 2bbeb67

Please sign in to comment.