[b612ab1] | 1 | import React, { useEffect, useReducer, useState } from "react";
|
---|
| 2 | import "../styles/Home.css";
|
---|
| 3 | // import data from "./data";
|
---|
| 4 | import Product from "../components/Product";
|
---|
| 5 | import axios from "axios";
|
---|
| 6 | import { Helmet } from "react-helmet-async";
|
---|
| 7 |
|
---|
| 8 | const reducer = (state, action) => {
|
---|
| 9 | switch (action.type) {
|
---|
| 10 | case "FETCH_REQUEST":
|
---|
| 11 | return { ...state, loading: true };
|
---|
| 12 | case "FETCH_SUCCESS":
|
---|
| 13 | return { ...state, products: action.payload, loading: false };
|
---|
| 14 | case "FETCH_FAIL":
|
---|
| 15 | return { ...state, loading: false, error: action.payload };
|
---|
| 16 | default:
|
---|
| 17 | return state;
|
---|
| 18 | }
|
---|
| 19 | };
|
---|
| 20 |
|
---|
| 21 | function Home() {
|
---|
| 22 | const [{ loading, error, products }, dispatch] = useReducer(reducer, {
|
---|
| 23 | products: [],
|
---|
| 24 | loading: true,
|
---|
| 25 | error: "",
|
---|
| 26 | });
|
---|
| 27 | //const [products, setProducts] = useState([]);
|
---|
| 28 | useEffect(() => {
|
---|
| 29 | const fetchData = async () => {
|
---|
| 30 | dispatch({ type: "FETCH_REQUEST" });
|
---|
| 31 | try {
|
---|
| 32 | const result = await axios.get("/api/products");
|
---|
| 33 | dispatch({ type: "FETCH_SUCCESS", payload: result.data });
|
---|
| 34 | } catch (err) {
|
---|
| 35 | dispatch({ type: "FETCH_FAIL", payload: err.message });
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | //setProducts(result.data);
|
---|
| 39 | };
|
---|
| 40 | fetchData();
|
---|
| 41 | }, []);
|
---|
| 42 |
|
---|
| 43 | return (
|
---|
| 44 | <div>
|
---|
| 45 | <Helmet>
|
---|
| 46 | <title>MebelCity</title>
|
---|
| 47 | </Helmet>
|
---|
| 48 |
|
---|
| 49 | <div className="most-popular-products">
|
---|
| 50 | {loading ? (
|
---|
| 51 | <div>Loading...</div>
|
---|
| 52 | ) : error ? (
|
---|
| 53 | <div>{error}</div>
|
---|
| 54 | ) : (
|
---|
| 55 | products.map((product) => (
|
---|
| 56 | <Product key={product.slug} product={product} />
|
---|
| 57 | ))
|
---|
| 58 | )}
|
---|
| 59 | </div>
|
---|
| 60 | </div>
|
---|
| 61 | );
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | export default Home;
|
---|