odin-codespace/shopping-cart/src/Store.jsx

56 lines
1.4 KiB
React
Raw Normal View History

2024-10-13 11:41:36 -04:00
import { useEffect, useState } from "react";
import ProductCollection from "./components/productCollection";
2024-10-14 07:23:02 -04:00
import { useOutletContext } from "react-router-dom";
2024-10-13 11:41:36 -04:00
2024-10-14 07:23:02 -04:00
export default function Store() {
2024-10-14 20:56:58 -04:00
const [cart, setCart, items, setItems] = useOutletContext();
2024-10-13 11:41:36 -04:00
const [loading, setLoading] = useState(true);
2024-10-15 06:47:25 -04:00
useFakeStoreAPIData(items, setItems, loading, setLoading);
return (
<div>
2024-10-17 12:34:45 -04:00
<h1>Smig.Tech Store</h1>
2024-10-15 06:47:25 -04:00
<ProductCollection
loading={loading}
items={items}
cart={cart}
setCart={setCart}
/>
</div>
);
}
function useFakeStoreAPIData(items, setItems, loading, setLoading) {
2024-10-13 11:41:36 -04:00
useEffect(() => {
2024-10-15 06:47:25 -04:00
if (items !== null) {
setLoading(false);
return;
}
2024-10-14 20:56:58 -04:00
2024-10-17 12:34:45 -04:00
fetch("https://fakestoreapi.com/products/category/electronics", {
mode: "cors",
})
2024-10-13 11:41:36 -04:00
.then((response) => {
if (response.status >= 400) {
2024-10-14 07:23:02 -04:00
throw new Error("unable to fetch items");
2024-10-13 11:41:36 -04:00
}
return response.json();
})
.then((response) => {
const arr = [];
response.forEach((item) => {
2024-10-14 07:23:02 -04:00
arr.push({
title: item.title,
2024-10-17 12:34:45 -04:00
price: item.price * 100,
2024-10-14 07:23:02 -04:00
image: item.image,
id: crypto.randomUUID(),
});
2024-10-13 11:41:36 -04:00
});
setItems(arr);
})
.catch((error) => console.log(error))
.finally(() => setLoading(false));
2024-10-15 06:47:25 -04:00
}, [items, setItems, loading, setLoading]);
2024-10-13 11:41:36 -04:00
}