Skip to content

Commit 07cd116

Browse files
richard-xue-vrxRichard XueRichard XueJessicaF
authored
(fix) duplicate SearchOptions being prepended to recentSearches array (#432)
* Fixed duplicate SearchOptions being prepended to recentSearches array * Ran prettier fix, w/ new search engine changes --------- Co-authored-by: Richard Xue <vrx@Richards-MBP.hub> Co-authored-by: Richard Xue <vrx@Richards-MacBook-Pro.local> Co-authored-by: Jessica Feng <54833118+JessicaF@users.noreply.github.com>
1 parent e2f5822 commit 07cd116

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

frontend/components/SearchModal.tsx

+22-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { useDispatch, useSelector } from "../redux/hooks";
2424
import { closeSearch, selectSearchOpen } from "../redux/searchOpenSlice";
2525
import { BuildingSearchOption, RoomSearchOption, SearchOption } from "../types";
2626

27+
const RECENT_SEARCH_LIMIT = 3;
2728
interface SearchProps {}
2829

2930
const SearchModal: React.FC<SearchProps> = () => {
@@ -36,8 +37,27 @@ const SearchModal: React.FC<SearchProps> = () => {
3637
"recentSearches",
3738
[]
3839
);
39-
const addRecentSearch = (option: SearchOption) => {
40-
setRecentSearches((prevState) => [option, ...prevState].slice(0, 3));
40+
41+
const addRecentSearch = (newOption: SearchOption) => {
42+
// Check if newOption for search already exists in previous state
43+
setRecentSearches((prevState) => {
44+
const prevIndex = prevState.findIndex((prevOption) => {
45+
if (newOption.type === "Building" && prevOption.type === "Building") {
46+
return prevOption.building.id === newOption.building.id;
47+
} else if (newOption.type === "Room" && prevOption.type === "Room") {
48+
return prevOption.room.id === newOption.room.id;
49+
}
50+
return false;
51+
});
52+
53+
const newState = [...prevState];
54+
if (prevIndex !== -1) {
55+
newState.splice(prevIndex, 1);
56+
}
57+
58+
newState.unshift(newOption);
59+
return newState.slice(0, RECENT_SEARCH_LIMIT);
60+
});
4161
};
4262

4363
// Fetch options

0 commit comments

Comments
 (0)