Skip to content

Commit

Permalink
fix(SearchBar): 밸리데이션 로직 수정
Browse files Browse the repository at this point in the history
- 검색어 없을 때 검색 안 되도록
  • Loading branch information
joojjang committed Nov 20, 2024
1 parent 89dcfaf commit 6cbaf88
Showing 1 changed file with 23 additions and 30 deletions.
53 changes: 23 additions & 30 deletions src/components/layouts/SearchBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,28 +57,30 @@ const SearchBar = ({ includeBack = true, includeFavorite = false, goBack }: Sear
const activeEnter = (data: { searchWord: string }) => {
const { searchWord } = data;

// 검색 기록 업데이트
const storedData = localStorage.getItem(SEARCH_ARRAY_KEY);
let searchArray = storedData ? JSON.parse(storedData) : [];
const existingIndex = searchArray.findIndex(
(item: { key: string; keyword: string }) => item.keyword === searchWord,
);

if (existingIndex !== -1) {
searchArray.splice(existingIndex, 1);
if (!formState.errors.searchWord) {
// 검색 기록 업데이트
const storedData = localStorage.getItem(SEARCH_ARRAY_KEY);
let searchArray = storedData ? JSON.parse(storedData) : [];
const existingIndex = searchArray.findIndex(
(item: { key: string; keyword: string }) => item.keyword === searchWord,
);

if (existingIndex !== -1) {
searchArray.splice(existingIndex, 1);
}

const newItem = { keyword: searchWord, key: generateRandomKey() };
searchArray = [newItem, ...searchArray];
if (searchArray.length > MAX_RECENT_SEARCHES) {
searchArray = searchArray.slice(0, MAX_RECENT_SEARCHES);
}

localStorage.setItem(SEARCH_ARRAY_KEY, JSON.stringify(searchArray));

// 검색 실행
setSearchParams({ query: searchWord });
navigate(`/${RouterPath.results}?query=${searchWord}`);
}

const newItem = { keyword: searchWord, key: generateRandomKey() };
searchArray = [newItem, ...searchArray];
if (searchArray.length > MAX_RECENT_SEARCHES) {
searchArray = searchArray.slice(0, MAX_RECENT_SEARCHES);
}

localStorage.setItem(SEARCH_ARRAY_KEY, JSON.stringify(searchArray));

// 검색 실행
setSearchParams({ query: searchWord });
navigate(`/${RouterPath.results}?query=${searchWord}`);
};

const nowSearchWord = watch('searchWord');
Expand All @@ -98,9 +100,6 @@ const SearchBar = ({ includeBack = true, includeFavorite = false, goBack }: Sear
/>
{nowSearchWord.trim().length > 0 && <CancelIconButton onClick={handleRemoveSearchWord} />}
</InputBox>
{formState.errors.searchWord && (
<ErrorMessage>{formState.errors.searchWord.message}</ErrorMessage>
)}
{includeFavorite && <IconButton icon="favorite-default" />}
</SearchBarWrapper>
);
Expand Down Expand Up @@ -162,9 +161,3 @@ const CancelIconButton = styled(CancelIcon)`
cursor: pointer;
color: var(--color-gray-dk);
`;

const ErrorMessage = styled.div`
color: red;
font-size: var(--font-size-sm);
margin-top: 4px;
`;

0 comments on commit 6cbaf88

Please sign in to comment.