diff --git a/src/App.tsx b/src/App.tsx index f3d58b606b..3df48a1954 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -18,14 +18,6 @@ import { Cart } from './pages/CartPage/Cart'; import { useLocalStorage } from './helpers/useLocalStorage'; import { useAppSelector } from './app/hooks'; -const visiblePhones = (query: string, phones: Phone[]) => { - const formattedQuery = query.trim().toLowerCase(); - - return phones.filter( - phone => phone.name.toLowerCase().includes(formattedQuery), - ); -}; - const visibleLikedPhones = (query: string, phones: Phone[]) => { const formattedQuery = query.trim().toLowerCase(); @@ -64,7 +56,6 @@ const App = () => { localStorage.setItem('cartItems', JSON.stringify(cartProducts)); }, [cartProducts]); - const visiblePhonesItems = visiblePhones(searchQuery, phones); const visibleLikedItems = visibleLikedPhones(searchQuery, likedProducts); return ( @@ -102,7 +93,7 @@ const App = () => { index element={( { } const handleSearch = (event: React.ChangeEvent) => { - const query = event.target.value.trim().toLowerCase(); + const query = event.target.value.toLowerCase(); dispatch(setQuery(query)); }; diff --git a/src/pages/PhonesPage/PhonesPage.tsx b/src/pages/PhonesPage/PhonesPage.tsx index 66695ffc2a..f2025e8f21 100644 --- a/src/pages/PhonesPage/PhonesPage.tsx +++ b/src/pages/PhonesPage/PhonesPage.tsx @@ -7,6 +7,7 @@ import { Phone } from '../../types/Phone'; import { CartItem } from '../../types/CartItem'; import './PhonesPage.scss'; import { NoResults } from '../NoResultsPage/NoResults'; +import { useAppSelector } from '../../app/hooks'; type Props = { phones: Phone[], @@ -17,14 +18,25 @@ type Props = { setCartProducts: React.Dispatch>, }; -const getSortedPhones = ( +const getSortedAndFilteredPhones = ( phones: Phone[], sortOption: string, currentPage: number, itemsPerPage: string, + searchQuery: string ) => { let visiblePhones = [...phones]; + if (searchQuery) { + const formattedQuery = searchQuery.trim().toLowerCase(); + const searchWords = formattedQuery.split(/\s+/); + + return phones.filter(phone => { + const phoneName = phone.name.toLowerCase(); + return searchWords.every(word => phoneName.includes(word)); + }); + } + visiblePhones.sort((a: Phone, b: Phone) => { if (sortOption === 'name') { return a.name.localeCompare(b.name); @@ -62,15 +74,20 @@ export const PhonesPage: React.FC = ({ const [itemsPerPage, setItemsPerPage] = useState('all'); const [sortOption, setSortOption] = useState('name'); const [currentPage, setCurrentPage] = useState(1); - - const visiblePhones = getSortedPhones( - phones, sortOption, currentPage, itemsPerPage, + const searchQuery = useAppSelector((state) => state.search.query).trim(); + + const visiblePhones = getSortedAndFilteredPhones( + phones, + sortOption, + currentPage, + itemsPerPage, + searchQuery ); return ( <>
- {!phones.length ? + {!visiblePhones.length ? : ( <> @@ -81,7 +98,7 @@ export const PhonesPage: React.FC = ({

- {`${phones.length} models`} + {`${visiblePhones.length} models`}