Untitled
unknown
jsx
3 years ago
2.6 kB
3
Indexable
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Categories from '../components/Categories'; import Sort from '../components/Sort'; import PizzaBlock from '../components/PizzaBlock'; import Skeleton from '../components/PizzaBlock/Skeleton'; import Pagination from '../components/Pagination'; import { SearchContext } from '../App'; import { setCategoryId, setSortType } from '../redux/slices/filterSlice'; export const Home = () => { const categoryId = useSelector((state) => state.filter.categoryId); const sortType = useSelector((state) => state.filter.sortType); const dispatch = useDispatch(); const { searchValue } = React.useContext(SearchContext); const [items, setItems] = React.useState([]); const [isLoading, setIsLoading] = React.useState(true); const [currentPage, setCurrentPage] = React.useState(1); const pizzas = items.map((pizza) => <PizzaBlock key={pizza.id} {...pizza} />); const skeletons = [...new Array(6)].map((_, index) => <Skeleton key={index} />); const onClickCategory = (index) => { dispatch(setCategoryId(index)); }; const onChangeSort = (sortType) => { console.log(sortType); dispatch(setSortType(sortType)); }; React.useEffect(() => { setIsLoading(true); const order = sortType.sortProperty.includes('-') ? 'asc' : 'desc'; const sortBy = sortType.sortProperty.replace('-', ''); const category = categoryId > 0 ? `category=${categoryId}` : ''; const search = searchValue ? `&search=${searchValue}` : ''; fetch( `https://632848ae9a053ff9aab45b88.mockapi.io/Item?page=${currentPage}&limit=4&${category}&sortBy=${sortBy}&order=${order}${search}`, ) .then((res) => { return res.json(); }) .then((json) => { setItems(json); setIsLoading(false); }); window.scrollTo(0, 0); }, [categoryId, sortType, searchValue, currentPage]); return ( <> <div className="container"> <div className="content__top"> <Categories value={categoryId} onChangeCategory={(index) => onClickCategory(index)} /> <Sort value={sortType} onChangeSort={(sortType) => onChangeSort(sortType)} /> </div> <h2 className="content__title">Все пиццы</h2> <div className="content__items">{isLoading ? skeletons : pizzas}</div> <Pagination onChangePage={(number) => setCurrentPage(number)} /> </div> </> ); }; export default Home;
Editor is loading...