Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 검색 기능을 최적화한다 #928

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';

import { useState } from 'react';

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

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

Expand All @@ -20,31 +15,19 @@ const StationSearchBar = () => {
handleCloseResult,
showStationDetails,
isFocused,
searchWord,
} = useStationSearchWindow();
const [debouncedSearchWord, setDebouncedSearchWord] = useState(searchWord);

useDebounce(
() => {
setDebouncedSearchWord(searchWord);
},
[searchWord],
400
);

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

return (
<StyledContainer>
<StyledForm role="search" onSubmit={handleSubmitSearchWord}>
<label htmlFor="station-search-bar" aria-hidden>
<StyledSearch
id="station-search-bar"
name="station-search"
type="search"
role="searchbox"
placeholder="충전소명 또는 지역명을 입력해 주세요"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ 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';

import { useNavigationBar } from '@ui/Navigator/NavigationBar/hooks/useNavigationBar';
Expand All @@ -24,54 +26,61 @@ import type { StationDetails, StationPosition } from '@type';
import StationDetailsWindow from '../../StationDetailsWindow/index';

export const useStationSearchWindow = () => {
const queryClient = useQueryClient();
const screen = useMediaQueries();

const [isFocused, setIsFocused] = useState(false);
const [searchWord, setSearchWord] = useState('');

const { renderDefaultMarker } = useMarker();
const queryClient = useQueryClient();

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

const { openLastPanel } = useNavigationBar();
const { openStationInfoWindow } = useStationInfoWindow();
const { renderDefaultMarker } = useMarker();

const screen = useMediaQueries();
useDebounce(
() => {
setDebouncedSearchWord(searchWord);
},
[searchWord],
400
);

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

const handleOpenResult = (
event?: MouseEvent<HTMLInputElement> | FocusEvent<HTMLInputElement>
) => {
if (event !== undefined) {
event.stopPropagation();
}

const handleOpenResult = (event: MouseEvent<HTMLInputElement> | FocusEvent<HTMLInputElement>) => {
event.stopPropagation();
setIsFocused(true);
};

const handleCloseResult = () => {
setIsFocused(false);
};

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

const searchedStations = await fetchSearchedStations(searchWord);

if (searchedStations !== undefined && searchedStations.stations.length > 0) {
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 });

if (!screen.get('isMobile')) {
openLastPanel(<StationDetailsWindow stationId={stationId} />);
}

// 지금 보여지는 화면에 검색한 충전소가 존재할 경우의 처리
if (
markerInstanceStore
.getState()
.some(({ id: cachedStationId }) => cachedStationId === stationId)
) {
const isStationInDisplayPosition = markerInstanceStore
.getState()
.some(({ id: cachedStationId }) => cachedStationId === stationId);

if (isStationInDisplayPosition) {
openStationInfoWindow(stationId);
} else {
const stationDetails = await fetch(
Expand All @@ -97,10 +106,46 @@ 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();

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

if (isSameAsPreviousSearchWord) {
return;
}

setUserSearchWord(encodedSearchWord);
Copy link
Member

@kyw0716 kyw0716 Nov 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이전 검색시 사용했던 검색어를 변화하는 현재 검색어와 비교해 같은 검색어는 새로운 요청을 발생시키지 않도록 하기 위해서 새로운 상태를 두어 해당 값을 캐시로 활용하고 계신거 같네요! 제가 이해한 내용이 맞다면 추가적인 상태를 늘려 훅의 복잡도가 높아질 여지가 있진 않을까 하는 생각이 듭니다.

현재 코드를 보면 검색 결과에 대한 쿼리를 등록하고 있으므로 해당 쿼리키에 해당하는 캐시 값이 있는지 여부를 통해 이전에 검색했던 값인지를 알아올 수도 있을 것 같아요! 아래 링크에 있는 메서드(queryClient.getQueryData)를 활용해도 괜찮을 것 같습니다 👍

쿼리키를 통해 캐시값을 읽어오는 메서드 참고 문서


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

return;
}

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

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

setIsFocused(true);
handleOpenResult();
setSearchWord(searchWord);
};

Expand All @@ -111,6 +156,10 @@ export const useStationSearchWindow = () => {
handleCloseResult,
showStationDetails,
isFocused,
searchWord,
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
4 changes: 2 additions & 2 deletions frontend/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useEffect, useCallback } from 'react';

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

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

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