feat: add save sessionStorage to scroll and category on shop
This commit is contained in:
@@ -7,9 +7,10 @@ import CardItem from "../components/CardItem";
|
||||
export default function Shop() {
|
||||
const [items, setItems] = useState([]);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [activeCategory, setActiveCategory] = useState("все");
|
||||
const [activeCategory, setActiveCategory] = useState(
|
||||
() => sessionStorage.getItem("shopCategory") || "все",
|
||||
);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([api.getAllItems(), api.getAllCategories()])
|
||||
.then(([itemsRes, categoriesRes]) => {
|
||||
@@ -24,16 +25,32 @@ export default function Shop() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
// восстановление скролла после загрузки товаров
|
||||
useEffect(() => {
|
||||
if (!loading && items.length > 0) {
|
||||
const saved = sessionStorage.getItem("shopScroll");
|
||||
if (saved) {
|
||||
window.scrollTo(0, parseInt(saved));
|
||||
sessionStorage.removeItem("shopScroll");
|
||||
}
|
||||
}
|
||||
}, [loading, items]);
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
return activeCategory === "все"
|
||||
? items || []
|
||||
: (items || []).filter((item) => {
|
||||
if (!item || !item.category) return false;
|
||||
|
||||
return item.category.toLowerCase() === activeCategory.toLowerCase();
|
||||
});
|
||||
}, [items, activeCategory]);
|
||||
|
||||
// сохранить позицию и категорию перед уходом на товар
|
||||
const handleNavigateToItem = () => {
|
||||
sessionStorage.setItem("shopScroll", window.scrollY);
|
||||
sessionStorage.setItem("shopCategory", activeCategory);
|
||||
};
|
||||
|
||||
const handleAddToCart = async (product, selectedWeight) => {
|
||||
try {
|
||||
await api.addToCart({
|
||||
@@ -48,11 +65,11 @@ export default function Shop() {
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return(
|
||||
return (
|
||||
<PageLayout>
|
||||
<p className="text-white grow">Загрузка...</p>
|
||||
</PageLayout>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -68,7 +85,12 @@ export default function Shop() {
|
||||
/>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 mb-4">
|
||||
{filteredItems.map((item) => (
|
||||
<CardItem key={item.id} item={item} onAddToCart={handleAddToCart} />
|
||||
<CardItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
onAddToCart={handleAddToCart}
|
||||
onNavigate={handleNavigateToItem}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
Reference in New Issue
Block a user