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

52 lines
1.3 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() {
const [cart, setCart] = useOutletContext();
2024-10-13 11:41:36 -04:00
const { items, loading } = useFakeStoreAPI();
2024-10-14 07:23:02 -04:00
2024-10-13 11:41:36 -04:00
return (
<div>
<h1>Smig.Tech Coaching Store</h1>
2024-10-14 07:23:02 -04:00
<ProductCollection
loading={loading}
items={items}
cart={cart}
setCart={setCart}
/>
2024-10-13 11:41:36 -04:00
</div>
);
}
function useFakeStoreAPI() {
const [items, setItems] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://fakestoreapi.com/products?limit=5", { mode: "cors" })
.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,
price: item.price,
image: item.image,
id: crypto.randomUUID(),
});
2024-10-13 11:41:36 -04:00
});
setItems(arr);
})
.catch((error) => console.log(error))
.finally(() => setLoading(false));
}, []);
return { items, loading };
}