Wednesday 10 May 2023

I have problem when fetaching data in Next js

In a Next.js project, the provided code fetches data from an external API endpoint and passes it as props to a component called Services. The Services component uses the received data to render different parts of the page based on the current URL pathname.

The data is fetched from the following API endpoint: http://back.menumizeme.com/api/get_business_info?business_id=1.

The useEffect hook is used to fetch the data when the component mounts. The useState hook is used to store the fetched data in the data state variable.

If the data has not been fetched yet, the Loading... message is displayed. Otherwise, the Services component is rendered with the data prop.

The Services component also uses a few other props, such as item and url, that are derived from the data prop to render different parts of the page based on the current URL pathname.

The Header component, which is rendered inside the Services component, displays the business logo and name. The CategorieItem and Categories components are used to display the list of categories and category items, respectively. The MyOrder component is used to display the current order.


import React, { useEffect, useState } from "react";
import Services from "../../components/Services/Services";

const ServicesPage = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(
          "http://back.menumizeme.com/api/get_business_info?business_id=1"
        );
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error("Error fetching data", error);
      }
    }

    fetchData();
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div className="container h-auto">
      <Services data={data} />
    </div>
  );
};

export default ServicesPage;

Services

import Image from "next/image";
import Header from "./Header";
import CategorieItem from "@/components/Services/Categorie-Item";
import Categories from "./Categories-List";
import { useRouter } from "next/router";
import MyOrder from "./MyOrder";

const Services = ({ data }) => {
  const serverBaseURI = "http://back.menumizeme.com";
  const router = useRouter();

  // if (!data || !data.data || !data.data[0] || !data.data[0].business) {
  //   return <div>Loading....</div>;
  // }
  const item = data.data[0];

  return (
    <section className="flex">
      <Image
        src={`${serverBaseURI}/storage/${item.business.business_logo}`}
        className="object-cover w-screen h-full"
        alt="Business Logo"
        width={1000}
        height={1000}
      />
      <div className="absolute flex flex-col w-full">
        <Header item={item} url={serverBaseURI} />
        {router.pathname === "/services" && (
          <div className="mt-3 ">
            {item.category_infos.map((category, index) => (
              <Categories key={index} category={category} item={item} />
            ))}
          </div>
        )}

        {/* {router.query && (
          <div className="mt-3">
            <CategorieItem key={router.query} item={} />
          </div>
        )}
        {router.pathname === "/myOrder/myOrder" && (
          <div className="mt-3">
            <MyOrder />
          </div>
        )} */}
      </div>
    </section>
  );
};

export default Services;

import React, { useState } from "react";
import { useRouter } from "next/router";
import { menuLink } from "./constants";
import Image from "next/image";
import { close, menu, basket } from "./assets";
import { MdLocationOn, MdPhone } from "react-icons/md";

const Header = ({ item, url }) => {
  const router = useRouter();
  const [toggle, setToggle] = useState(false);

  return (
    <div className="flex flex-row w-full justify-between">
      <div className="flex">
        <Image
          src={toggle ? close : menu}
          alt="menu"
          className="w-[32px] h-[32px] mr-1 object-contain ml-[30px] mt-12 cursor-pointer"
          onClick={() => setToggle((prev) => !prev)}
        />
        <div
          className={`${
            toggle ? "flex" : "hidden"
          } bg-[#000000f1] absolute top-20 w-[98.5vw] sidebar z-[1]`}
        >
          <ul className="list-none flex flex-col justify-end items-center flex-1">
            {menuLink.map((nav, index) => (
              <li
                key={nav.id}
                className={`font-poppins font-semibold border-[#ffffff83] w-[98.5vw] cursor-pointer flex flex-col justify-center h-12 text-[18px] leading-7 text-white text-center hover:text-[#FAB25A] hover:font-bold hover:bg-[#fab25a2d] ${
                  index === menuLink.length - 1 ? "" : "border-b-[1px]"
                }`}
              >
                <a href={`#${nav.id}`}>{nav.title}</a>
              </li>
            ))}
          </ul>
        </div>
      </div>
      <div className="mt-10 flex flex-col">
        <Image
          src={`${url}/storage/${item.data.business_logo}`}
          className="object-contine"
          alt="Business Logo"
          width={1000}
          height={1000}
        />
        {router.pathname === "/services" && (
          <p className="font-Montserrat font-[700] text-lg text-[#FEFEFE] capitalize">
            {item.data.name} {item.data.businessType}
          </p>
        )}
        {router.pathname === "/services" && (
          <div className="flex-col mt-14 mx-2">
            <div className="flex flex-row mt-2">
              <MdLocationOn
                color="#A8A8A8"
                className="w-[20px] h-[20px] mt-1 mr-2"
              />
              <p className="font-Montserrat font-[400] text-lg text-[#A8A8A8]">
                {item.data.address}
              </p>
            </div>
            <div className="flex flex-row mt-2">
              <MdPhone
                color="#A8A8A8"
                className="w-[20px] h-[20px] mt-1 mr-2"
              />
              <p className="font-Montserrat font-[400] text-lg text-[#A8A8A8]">
                {item.data.phone_number}
              </p>
            </div>
          </div>
        )}
      </div>
      <div className="mr-[30px] mt-12">
        <Image src={basket} className="cursor-pointer" alt="Basket" />
      </div>
    </div>
  );
};

export default Header;

Categories

import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { useRouter } from "next/router";

const Categories = ({ category }) => {
  const router = useRouter();

  const [selectedCategory, setSelectedCategory] = useState(null);

  const handleCategoryClick = (category_id) => {
    setSelectedCategory(category_id);
    console.log(category_id);
  };

  return (
    <div className="flex flex-col">
      <Link href={`/services/${category.id}`} key={category.id}>
        <div className="flex mt-2 justify-center items-center cursor-pointer transition duration-300 ease-in-out hover:scale-110">
          {/* <Image
            src={item.logo}
            className="object-fill w-full h-[7.5rem]"
            alt={category.name}
          /> */}
          <div className="absolute w-full h-[7.5rem] flex flex-col justify-center items-center bg-[#00000054] ">
            <p className="font-Montserrat font-[700] text-[30px] leading-9 text-[#FEFEFE] capitalize ">
              {category.name}
            </p>
            <p className="font-Montserrat font-[400] text-[12px] text-[#FEFEFE] leading-3 capitalize mt-1">
              {category.description}
            </p>
          </div>
        </div>
      </Link>
    </div>
  );
};

export default Categories;

CategorieItem

import { resturant } from "@/constant/resturant";
import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import ModalOrder from "./Modal/ModalOrder";

const CategorieItem = ({ resturant }) => {
  const { query } = useRouter();
  const item = resturant;
  const [productsToShow, setProductsToShow] = useState([]);
  const [showModal, setShowModal] = useState(false);
  
  useEffect(() => {
    query?.params &&
      setProductsToShow(
        item.categories.find(
          (category) => parseInt(category.id) === parseInt(query?.params[0])
        )?.products || []
      );
  }, [query]);

  return (
    <section>
      <div className="flex flex-col">
        {productsToShow?.map((product, index) => (
          <div>
            <div
              key={index}
              className="flex flex-row w-[22rem] h-[11rem] justify-between item-center cursor-pointer mt-4 mx-auto "
              onClick={() => setShowModal(true)}
            >
              <div>
                <Image
                  src={product.image}
                  className="w-[11rem] h-[11rem] absolute cursor-pointer transition duration-300 ease-in-out hover:scale-110 rounded-full"
                />
              </div>
              <div className="flex flex-col justify-center pl-9 items-start w-[13rem] h-[8rem] bg-gradient-to-l from-[#ffffffb7] rounded-r-[13rem] my-auto ">
                <h2 className="font-Montserrat text-[#fff]  font-bold text-lg leading-5">
                  {product.name}
                </h2>
                <p className="font-Montserrat text-[#fff] font-[500] text-[12px] leading-4 my-2">
                  {product.description}
                </p>
                <p className="font-Montserrat text-[#fff] font-bold text-lg leading-5">
                  {product.price}
                </p>
              </div>
            </div>

            <div>
              <ModalOrder product={product} showModal={showModal} setShowModal={setShowModal}/>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

export default CategorieItem;

can any one help me I got a lot of error



from I have problem when fetaching data in Next js

No comments:

Post a Comment