@@ -24,6 +24,7 @@ import { useDispatch, useSelector } from "../redux/hooks";
24
24
import { closeSearch , selectSearchOpen } from "../redux/searchOpenSlice" ;
25
25
import { BuildingSearchOption , RoomSearchOption , SearchOption } from "../types" ;
26
26
27
+ const RECENT_SEARCH_LIMIT = 3 ;
27
28
interface SearchProps { }
28
29
29
30
const SearchModal : React . FC < SearchProps > = ( ) => {
@@ -36,8 +37,27 @@ const SearchModal: React.FC<SearchProps> = () => {
36
37
"recentSearches" ,
37
38
[ ]
38
39
) ;
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
+ } ) ;
41
61
} ;
42
62
43
63
// Fetch options
0 commit comments