javascript - NextJs fetch API problem and lang parameter with i18n - Stack Overflow

I have created a not very dynamic site with the latest version of nextjs. So the folder structure is ap

I have created a not very dynamic site with the latest version of nextjs. So the folder structure is app/(home)/page.tsx and app/(home)/page.tsx. What is my problem? I want to fetch the endpoint in a section of the home page, and I have also added the language switcher in header with i18n, but that language should be sent as a parameter so that the data appropriate for that language is dynamic data in section. I don't know exactly how to do it.

import React from "react";
import About from "./sections/About";
import Videos from "./sections/Videos";
import Gallery from "./sections/Gallery";
import Carousel from "./sections/Carousel";
import Banner from "./sections/Banner";
import Intro from "./sections/Intro";
import { fetchNews } from "@/services/galleryService";
interface Image {
  id: string;
  imageUrl: string;
  isCover: boolean;
}

interface GalleryD {
  id: string;
  isDraft: boolean;
  images: Image[];
  domains: {
    id: string;
    url: string;
    languages: {
      languageId: string;
      name: string;
    }[];
  }[];
  languages: {
    languageId: string;
    description: string;
  }[];
}

interface GalleryProps {
  galleryData: {
    totalCount: number;
    galeries: GalleryD[];
  };
  currentLanguage: string;
}

// const fetchNews = async (
//   language: string
// ): Promise<{
//   totalCount: number;
//   galeries: Gallery[];
// }> => {
//   try {
//     process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
//     const response = await fetch(
//       `${process.env.NEXT_PUBLIC_API_URL}/api/Galery/GetAll?language=${language}`,
//       {
//         cache: "no-store",
//       }
//     );
//     console.log("Fetching news data...");
//     console.log(response);

//     if (!response.ok) {
//       throw new Error(
//         `Server error: ${response.status} ${response.statusText}`
//       );
//     }
//     const data = await response.json();
//     console.log(data);

//     return data;
//   } catch (error) {
//     console.error("Error fetching news:", error);
//     throw error;
//   }
// };

const Home = async ({
  currentLanguage = "az",
}: {
  currentLanguage: string;
}) => {
  const galleryData = await fetchNews(currentLanguage);
  return (
    <>
      <Intro />
      <About />
      <Carousel />
      <Banner />
      <Gallery galleryData={galleryData} currentLanguage={currentLanguage} />
      <Videos />
    </>
  );
};

export default Home;
import type { Metadata } from "next";
import { Mulish } from "next/font/google";
import "./globals.css";
import Header from "@/layouts/Header";
import Footer from "@/layouts/Footer";
import Navbar from "@/layouts/Navbar";
import React from "react";
import i18n from "@/i18n/i18next";
import { dir } from "i18next";

const mulish = Mulish({
  subsets: ["latin"],
  weight: ["400", "600", "700", "300", "800", "200"],
});

interface Props {
  children: React.ReactNode;
  params: { locale: string };
}

export const metadata: Metadata = {
  title:
    "ddd",
  description: "ddd",
};
export default function RootLayout({ children, params }: Props) {
  const currentLocale = params.locale || "az";
  return (
    <html lang={currentLocale} dir={currentLocale === "az" ? "ltr" : "ltr"}>
      <body className={mulish.className}>
        <Header />
        <Navbar currentLanguage={currentLocale} />
        <main>{children}</main>
        <Footer />
      </body>
    </html>
  );
}
"use client";

import React, { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import styles from "./style.module.css";
import { ChevronDownIcon } from "@/assets/icons";
import i18n from "@/i18n/i18next";

const Dropdown: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const { t } = useTranslation();
  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleDropdown = () => setIsOpen((prev) => !prev);

  const handleLanguageChange = (language: string) => {
    i18n.changeLanguage(language);
    setIsOpen(false);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <>
      <div className={styles.dropdown} ref={dropdownRef}>
        <button className={styles.dropdownButton} onClick={toggleDropdown}>
          {i18n?.language?.toUpperCase()}
          <ChevronDownIcon size={21} />
        </button>
        {isOpen && (
          <ul className={styles.dropdownMenu}>
            <li
              className={styles.dropdownItem}
              onClick={() => handleLanguageChange("az")}
            >
              AZ
            </li>
            <li
              className={styles.dropdownItem}
              onClick={() => handleLanguageChange("en")}
            >
              EN
            </li>
          </ul>
        )}
      </div>
    </>
  );
};

export default Dropdown;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745350138a4623782.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信