frontend: reduce code in index page.js file

This commit is contained in:
Kentai Radiquum 2024-04-21 01:32:27 +05:00
parent 227bada365
commit 732799703d
Signed by: Radiquum
GPG key ID: 858E8EE696525EED

View file

@ -5,7 +5,6 @@ import { endpoints } from "./api/config";
import { useEffect, useState, useCallback } from "react";
import { usePathname, useRouter } from "next/navigation";
import { CardList } from "./components/CardList/CardList";
import { useSearchParams } from "next/navigation";
export default function Home() {
@ -27,71 +26,72 @@ export default function Home() {
[searchParams]
);
// set list on initial page load
useEffect(() => {
setList(searchParams.get("list") || "last");
}, []);
async function getReleases() {
const data = await getData(`${endpoints.index[list]}`);
setReleases(data.content);
}
async function getPage() {
const data = await getData(`${endpoints.index[list]}?page=${page}`);
setReleases([...releases, ...data.content]);
async function fetchData(list, page = 0) {
const url = `${endpoints.index[list]}?page=${page}`;
const data = await getData(url);
// Handle initial load (page 0) or subsequent pagination
if (page === 0) {
setReleases(data.content);
} else {
setReleases([...releases, ...data.content]);
}
}
useEffect(() => {
router.push(pathname + "?" + createQueryString("list", list));
setReleases(null);
setPage(0);
if (list) {
getReleases();
}
fetchData(list); // Call fetchData here
}, [list]);
useEffect(() => {
if (list && releases) {
getPage();
fetchData(list, page); // Use fetchData for pagination
}
}, [page]);
const chips = [
{
title: "последнее",
list: "last",
},
{
title: "в эфире",
list: "ongoing",
},
{
title: "анонсировано",
list: "announce",
},
{
title: "завершено",
list: "finished",
},
];
return (
<>
<div>
<button
className={`chip ${list == "last" ? "fill" : ""}`}
onClick={() => {
setList("last");
}}
>
<span>последнее</span>
</button>
<button
className={`chip ${list == "ongoing" ? "fill" : ""}`}
onClick={() => {
setList("ongoing");
}}
>
<span>в эфире</span>
</button>
<button
className={`chip ${list == "announce" ? "fill" : ""}`}
onClick={() => {
setList("announce");
}}
>
<span>анонсировано</span>
</button>
<button
className={`chip ${list == "finished" ? "fill" : ""}`}
onClick={() => {
setList("finished");
}}
>
<span>завершено</span>
</button>
{chips.map((item) => {
return (
<button
className={`chip ${list == item.list ? "fill" : ""}`}
onClick={() => {
setList(item.list);
}}
>
<span>{item.title}</span>
</button>
);
})}
</div>
{releases ? (
<>
<div className="grid">