Commit ee34d3ad by Madhankumar

fetch from server

parent 9fa4af0d
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import BlogLists from "@components/top-level/blog-lists"; import BlogLists from "@components/top-level/blog-lists";
import Loading from "./loading";
import { useAppContext } from "@context/index"; import { useAppContext } from "@context/index";
import styles from "./container.module.css"; import styles from "./container.module.css";
export default function BlogContainer({ blogs }) { export default function BlogContainer({ blogs }) {
const { input } = useAppContext(); const { input } = useAppContext();
const [filteredBlogs, setFilteredBlogs] = useState([]); const [filteredBlogs, setFilteredBlogs] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
handleBlogs(); handleBlogs();
}, [input, blogs]); // Added 'blogs' as a dependency }, [input, blogs]); // Added 'blogs' as a dependency
const handleBlogs = () => { const handleBlogs = () => {
setLoading(true); // Set loading state to true when starting to filter
const filtered = blogs.filter((blog) => { const filtered = blogs.filter((blog) => {
const lowerCaseBlogTitle = blog.title.toLowerCase(); const lowerCaseBlogTitle = blog.title.toLowerCase();
const lowerCaseInput = input.toLowerCase(); const lowerCaseInput = input.toLowerCase();
...@@ -20,11 +24,14 @@ export default function BlogContainer({ blogs }) { ...@@ -20,11 +24,14 @@ export default function BlogContainer({ blogs }) {
}); });
setFilteredBlogs(filtered); setFilteredBlogs(filtered);
setLoading(false); // Set loading state to false when filtering is complete
}; };
console.log("dfh", filteredBlogs);
return ( return (
<> <>
{filteredBlogs.length ? ( {loading ? (
<Loading />
) : filteredBlogs.length ? (
<BlogLists <BlogLists
title="Lifestyle" title="Lifestyle"
description="Lorem ipsum dolor sit amet elit. Id quaerat amet ipsum sunt et quos dolorum." description="Lorem ipsum dolor sit amet elit. Id quaerat amet ipsum sunt et quos dolorum."
......
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { ThemeProvider } from "@context/index"; import { ThemeProvider } from "@context/index";
import Loading from "./loading";
import "./globals.css"; import "./globals.css";
export default function RootLayout({ children, header }) { export default function RootLayout({ children, header }) {
const [themeClass, setThemeClass] = useState("loading"); // Check if localStorage is available (client-side)
const themeClass =
useEffect(() => { typeof window !== "undefined" ? localStorage.getItem("theme") : "light";
// Check if localStorage is available (client-side)
const storedThemeClass =
typeof window !== "undefined" ? localStorage.getItem("theme") : "";
// Simulate an asynchronous operation (e.g., fetching theme data)
setTimeout(() => {
// Set the theme class, or use a default value if not found
setThemeClass(storedThemeClass || "defaultTheme");
}, 1000); // Adjust the delay as needed
}, []); // Empty dependency array ensures the effect runs once, similar to componentDidMount
return ( return (
<ThemeProvider> <ThemeProvider>
<html lang="en" className={themeClass}> <html lang="en" className={themeClass}>
<body> <body>
{themeClass === "loading" ? ( <div id="root">
<Loading /> {header}
) : ( {children}
<div id="root"> </div>
{header}
{children}
</div>
)}
</body> </body>
</html> </html>
</ThemeProvider> </ThemeProvider>
......
"use client";
import React, { useState, useEffect } from "react";
import BlogContainer from "./container"; import BlogContainer from "./container";
import Loading from "./loading"; import { getAllPosts } from "@lib/posts";
import styles from "./page.module.css"; import styles from "./page.module.css";
import Loading from "./loading";
const Home = () => { const Home = () => {
const [loading, setLoading] = useState(true); let blogs;
const [blogs, setBlogs] = useState([]); const fetchData = () => {
try {
useEffect(() => { blogs = getAllPosts("posts");
const fetchData = async () => { } catch (error) {
try { console.error("Error fetching blogs:", error);
const response = await fetch(`http://localhost:3000/api/posts`); }
const fetchedBlogs = await response.json(); };
setBlogs(fetchedBlogs);
setLoading(false);
} catch (error) {
console.error("Error fetching blogs:", error);
}
};
fetchData(); fetchData();
}, []);
return ( return (
<div className={styles.container}> <div className={styles.container}>
{loading ? <Loading /> : <BlogContainer blogs={blogs} />} {blogs.length ? <BlogContainer blogs={blogs} /> : <Loading />}
</div> </div>
); );
}; };
......
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import Icons from "@components/base/icons"; import Icons from "@components/base/icons";
import styles from "./styles.module.css"; import styles from "./styles.module.css";
...@@ -53,4 +54,8 @@ const Search = ({ onSearch, onClose }) => { ...@@ -53,4 +54,8 @@ const Search = ({ onSearch, onClose }) => {
); );
}; };
Search.propTypes = {
onSearch: PropTypes.func,
onClose: PropTypes.func,
};
export default Search; export default Search;
"use client"; "use client";
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import Card from "@components/base/card"; import Card from "@components/base/card";
import Pagination from "@components/top-level/pagination"; import Pagination from "@components/top-level/pagination";
import { useSearchParams } from "next/navigation";
import styles from "./styles.module.css"; import styles from "./styles.module.css";
const BlogLists = ({ title, description, blogs }) => { const BlogLists = ({ title, description, blogs }) => {
console.log("xfkjhb", blogs); const searchParams = useSearchParams();
let searchPage = searchParams.get("page");
console.log("iuh", searchPage);
const length = blogs.length; const length = blogs.length;
const itemsPerPage = 6; const itemsPerPage = 6;
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(searchPage);
// Calculate the start and end indices for the current page // Calculate the start and end indices for the current page
const startIndex = blogs.length > 6 ? (currentPage - 1) * itemsPerPage : 0; const startIndex = blogs.length > 6 ? (currentPage - 1) * itemsPerPage : 0;
const endIndex = startIndex + itemsPerPage; const endIndex = startIndex + itemsPerPage;
const slicedData = blogs.slice(startIndex, endIndex); const slicedData = blogs.slice(startIndex, endIndex);
useEffect(() => {
setCurrentPage(parseInt(searchPage));
}, [searchPage]);
// Handle page change // Handle page change
const handlePageChange = (pageNumber) => { const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber); setCurrentPage(pageNumber);
...@@ -23,7 +29,7 @@ const BlogLists = ({ title, description, blogs }) => { ...@@ -23,7 +29,7 @@ const BlogLists = ({ title, description, blogs }) => {
return ( return (
<div className={styles["blog-container"]}> <div className={styles["blog-container"]}>
<h1 className={styles.title}>{title}</h1> <h2 className={styles.title}>{title}</h2>
<p className={styles.description}>{description}</p> <p className={styles.description}>{description}</p>
<div className={styles.row}> <div className={styles.row}>
{slicedData.map((blogData, i) => ( {slicedData.map((blogData, i) => (
......
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import Button from "@components/base/button"; import Button from "@components/base/button";
import { useRouter } from "next/navigation";
import styles from "./styles.module.css"; import styles from "./styles.module.css";
function Pagination({ total, currentPage, onPageChange, perPage }) { function Pagination({ total, currentPage, onPageChange, perPage }) {
const router = useRouter();
//Set number of pages //Set number of pages
const numberOfPages = []; const numberOfPages = [];
const totalPages = Math.ceil(total / perPage); const totalPages = Math.ceil(total / perPage);
const totalPage = totalPages <= 1 ? 1 : totalPages; const totalPage = totalPages <= 1 ? 1 : totalPages;
for (let i = 1; i <= totalPage; i++) { for (let i = 1; i <= totalPage; i++) {
numberOfPages.push(i); numberOfPages.push(i);
...@@ -56,6 +57,8 @@ function Pagination({ total, currentPage, onPageChange, perPage }) { ...@@ -56,6 +57,8 @@ function Pagination({ total, currentPage, onPageChange, perPage }) {
//update currentButton value if currentPageNo changes //update currentButton value if currentPageNo changes
useEffect(() => { useEffect(() => {
setCurrentButton(currentPage); setCurrentButton(currentPage);
router.push(`/?page=${currentPage}`);
}, [currentPage]); }, [currentPage]);
//onClick function //onClick function
......
...@@ -16,7 +16,7 @@ function SingleBlog({ ...@@ -16,7 +16,7 @@ function SingleBlog({
return ( return (
<div className={styles["container"]}> <div className={styles["container"]}>
<div className={styles.headtitle}> <div className={styles.headtitle}>
<h2 className={styles.title}>{title}</h2> <h1 className={styles.title}>{title}</h1>
</div> </div>
<div className={styles["blog-list"]}> <div className={styles["blog-list"]}>
<ul> <ul>
...@@ -71,9 +71,9 @@ function SingleBlog({ ...@@ -71,9 +71,9 @@ function SingleBlog({
SingleBlog.propTypes = { SingleBlog.propTypes = {
title: PropTypes.string, title: PropTypes.string,
publishedDate: PropTypes.string, publishedDate: PropTypes.string,
author: { author: PropTypes.shape({
name: PropTypes.string, name: PropTypes.string,
}, }),
blogImage: PropTypes.shape({ blogImage: PropTypes.shape({
url: PropTypes.string, url: PropTypes.string,
width: PropTypes.number, width: PropTypes.number,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment