Commit 733dd1d5 by Sakilesh J

fix the bugs

parent d14d7581
NEXT_PUBLIC_API_URL=http://localhost:4000/ NEXT_PUBLIC_API_URL='http://192.168.1.161:3000'
// app/api/hello/route.js // app/api/hello/route.js
import { getAllPosts } from '@/lib/posts';
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { getAllPosts } from '@/lib/posts';
export async function GET() { export async function GET() {
const Data = getAllPosts(); const Data = getAllPosts(); // Fetch your data here
return NextResponse.json({ Data });
// Create a response with CORS headers
const response = NextResponse.json({ Data });
// Add CORS headers
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
return response;
}
export async function OPTIONS() {
// CORS preflight response
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*', // Adjust as needed
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400', // 24 hours
},
});
} }
const Loader = () => {
return (<div className="w-32 h-32 border-6 p-[50px] border-b-white dark:border-b-black dark:border-white border-black animate-spin"></div>
);
}
export default Loader;
\ No newline at end of file
'use client'; 'use client';
import { pageData } from "@/utils/Data";
import axios from "axios"; import axios from "axios";
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { createContext,useState } from "react"; import { createContext,useState } from "react";
...@@ -8,7 +7,7 @@ type ContextType= { ...@@ -8,7 +7,7 @@ type ContextType= {
ToggleTheme: () => void; ToggleTheme: () => void;
data:{ data:{
id: number; id: number;
blogTitle: string; title: string;
authorDetails: { authorDetails: {
author: string; author: string;
date: Date; date: Date;
...@@ -31,6 +30,7 @@ type ContextType= { ...@@ -31,6 +30,7 @@ type ContextType= {
size: number; size: number;
currentPage: number; currentPage: number;
handleChangePage: (page: number) => void; handleChangePage: (page: number) => void;
isLoading:boolean
} }
export const Context = createContext<ContextType>({ export const Context = createContext<ContextType>({
start: 1, start: 1,
...@@ -38,10 +38,11 @@ export const Context = createContext<ContextType>({ ...@@ -38,10 +38,11 @@ export const Context = createContext<ContextType>({
size: 1, size: 1,
currentPage: 1, currentPage: 1,
handleChangePage: () => { }, handleChangePage: () => { },
data: pageData, data: [],
handleFilter: () => { }, handleFilter: () => { },
theme: 'dark', theme: 'dark',
ToggleTheme:()=>{} ToggleTheme: () => { },
isLoading: false
}) })
interface AppContextProps{ interface AppContextProps{
children: React.ReactNode children: React.ReactNode
...@@ -61,17 +62,20 @@ const AppContext = ({ children }: AppContextProps) => { ...@@ -61,17 +62,20 @@ const AppContext = ({ children }: AppContextProps) => {
setstart((page - 1) * size); setstart((page - 1) * size);
setend(page * size); setend(page * size);
} }
const [filter, setFilter] = useState<any>([]); const [filter, setFilter] = useState([]);
const [pageData, setPageData] = useState<any>([]); const [pageData, setPageData] = useState([]);
const [isLoading, setisLoading] = useState(false);
// Fetch data from API and set state // Fetch data from API and set state
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchData = async () => {
try { try {
const res = await axios.get('http://localhost:3000/api/'); setisLoading(true);
const res = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/`);
setPageData(res.data.Data); setPageData(res.data.Data);
setFilter(res.data.Data); // Set filter with fetched data setFilter(res.data.Data); // Set filter with fetched data
} catch (error) { setisLoading(false);
} catch (error) {
setisLoading(false);
console.error("Error fetching data:", error); console.error("Error fetching data:", error);
} }
}; };
...@@ -80,13 +84,14 @@ const AppContext = ({ children }: AppContextProps) => { ...@@ -80,13 +84,14 @@ const AppContext = ({ children }: AppContextProps) => {
}, []); }, []);
// Handle filtering of data based on search input // Handle filtering of data based on search input
const handleFilter = (search:string) => { const handleFilter = (search: string) => {
if (search.trim() === "") { if (search.trim() === "") {
setFilter(pageData); setFilter(pageData);
} else { } else {
setFilter( setFilter(
pageData.filter((data:any) => pageData.filter((data:any) =>
data.blogTitle.toLowerCase().includes(search.toLowerCase()) data.title.toLowerCase().includes(search.toLowerCase())
) )
); );
} }
...@@ -101,6 +106,7 @@ const AppContext = ({ children }: AppContextProps) => { ...@@ -101,6 +106,7 @@ const AppContext = ({ children }: AppContextProps) => {
size, size,
currentPage, currentPage,
handleChangePage, handleChangePage,
isLoading
}}> }}>
{children} {children}
</Context.Provider> ); </Context.Provider> );
......
module.exports = { module.exports = {
images: { images: {
domains:['cdn.pixabay.com','images.pexels.com'], domains:['cdn.pixabay.com','images.pexels.com'],
...@@ -26,10 +28,24 @@ module.exports = { ...@@ -26,10 +28,24 @@ module.exports = {
return [ return [
{ {
source: '/api/:path*', source: '/api/:path*',
destination: `${process.env.NEXT_PUBLIC_API_URL}/:path*` destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`,
} }
]; ];
}, },
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
{ key: "Access-Control-Allow-Methods", value:'GET, POST, PUT, DELETE, OPTIONS' },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
},
poweredByHeader: false, poweredByHeader: false,
compress: false, compress: false,
}; };
'use client' 'use client'
import Heading from "@/components/base/Heading/Heading"; import Heading from "@/components/base/Heading/Heading";
import Loader from "@/components/base/loader/Loader";
import BlogCard from "@/components/Top-Level/blog-card/BlogCard"; import BlogCard from "@/components/Top-Level/blog-card/BlogCard";
import Pagination from "@/components/Top-Level/pagination/pagination"; import Pagination from "@/components/Top-Level/pagination/pagination";
import { Context } from "@/hooks/AppContext"; import { Context } from "@/hooks/AppContext";
...@@ -9,7 +10,7 @@ import { useContext, useEffect, useState } from "react"; ...@@ -9,7 +10,7 @@ import { useContext, useEffect, useState } from "react";
const Home = () => { const Home = () => {
const [isMounted, setisMounted] = useState(false) const [isMounted, setisMounted] = useState(false)
const router = useRouter(); const router = useRouter();
const {data, size, currentPage, start, end, handleChangePage } = useContext(Context); const {data, size, currentPage, start, end, handleChangePage,isLoading } = useContext(Context);
useEffect(() => { useEffect(() => {
setisMounted(true); setisMounted(true);
}, []) }, [])
...@@ -17,23 +18,24 @@ const Home = () => { ...@@ -17,23 +18,24 @@ const Home = () => {
if (!isMounted) { if (!isMounted) {
return null return null
} }
console.log(data)
return ( return (
<div className="max-w-[1100px] mx-auto px-4 "> <div className="max-w-[1100px] mx-auto px-4 ">
<Heading /> <Heading />
<div className="flex flex-wrap gap-6 w-full dark:bg-black mt-4"> <div className="flex flex-wrap gap-6 w-full dark:bg-black mt-4">
{ {
data.length === 0 && <h2 className=" capitalize dark:text-white text-center w-full text-2xl font-semibold py-5">no Data found</h2> isLoading && <Loader />
}
{
!isLoading && data?.length === 0 && <h2 className=" capitalize dark:text-white text-center w-full text-2xl font-semibold py-5">no Data found</h2>
} }
{data?.slice(start,end).map((data) => ( {data?.slice(start,end).map((data) => (
<div key={data.id} className="flex-grow sm:flex-grow-0 sm:w-[calc(50%-1rem)] <div key={data.id} className="flex-grow sm:flex-grow-0 sm:w-[calc(50%-1rem)]
lg:w-[calc(33.33%-1rem)] *:sm:max-w-full *:h-full"> lg:w-[calc(33.33%-1rem)] *:sm:max-w-full *:h-full">
<BlogCard { <BlogCard {
...{ ...{
title: data.blogTitle,
img: data.banner.img, img: data.banner.img,
...data.authorDetails, ...data.authorDetails,
date:new Date(data.authorDetails.date), date:new Date(data?.authorDetails.date),
...data, ...data,
} }
} handleClick={() => { } handleClick={() => {
...@@ -43,8 +45,7 @@ const Home = () => { ...@@ -43,8 +45,7 @@ const Home = () => {
))} ))}
</div> </div>
<center className="w-full p-2 sm:p-4 md:p-6 flex justify-center "> <center className="w-full p-2 sm:p-4 md:p-6 flex justify-center ">
<Pagination size={Math.ceil(data <Pagination size={Math.ceil(data?.length / size)} onChange={handleChangePage} currentPage={currentPage} />
.length / size)} onChange={handleChangePage} currentPage={currentPage} />
</center> </center>
</div > </div >
......
...@@ -33,7 +33,7 @@ interface BlogData { ...@@ -33,7 +33,7 @@ interface BlogData {
} }
const Blog: React.FC<BlogProps> = async ({ id }) => { const Blog: React.FC<BlogProps> = async ({ id }) => {
const res = await axios.get<BlogData>('http://localhost:3000/api/'); const res = await axios.get<BlogData>(`${process.env.NEXT_PUBLIC_API_URL}/api/`);
const data = res.data.Data; const data = res.data.Data;
console.log(data) console.log(data)
const blogData = data.find(item => item.id === id); const blogData = data.find(item => item.id === id);
......
--- ---
id: 11 id: 11
blogTitle: "The Ultimate Guide to Adventure Travel" title: "The Ultimate Guide to Adventure Travel"
authorDetails: authorDetails:
author: "Jane Smith" author: "Jane Smith"
date: "2021-01-15" date: "2021-01-15"
......
--- ---
id: 12 id: 12
blogTitle: "10 Must-Visit Destinations in Africa" title: "10 Must-Visit Destinations in Africa"
authorDetails: authorDetails:
author: "Alex Johnson" author: "Alex Johnson"
date: "2021-05-10" date: "2021-05-10"
......
--- ---
id: 13 id: 13
blogTitle: "Boost Your Productivity with These Office Hacks" title: "Boost Your Productivity with These Office Hacks"
authorDetails: authorDetails:
author: "Emily Davis" author: "Emily Davis"
date: "2021-07-21" date: "2021-07-21"
......
--- ---
id: 14 id: 14
blogTitle: "Healthy Eating: 7 Delicious Salad Recipes" title: "Healthy Eating: 7 Delicious Salad Recipes"
authorDetails: authorDetails:
author: "Michael Lee" author: "Michael Lee"
date: "2021-08-30" date: "2021-08-30"
......
--- ---
id: 15 id: 15
blogTitle: "Top Hiking Trails for Beginners" title: "Top Hiking Trails for Beginners"
authorDetails: authorDetails:
author: "Sophia Martinez" author: "Sophia Martinez"
date: "2022-01-20" date: "2022-01-20"
......
--- ---
id: 16 id: 16
blogTitle: "Understanding Asynchronous JavaScript" title: "Understanding Asynchronous JavaScript"
authorDetails: authorDetails:
author: "David Robinson" author: "David Robinson"
date: "2022-03-05" date: "2022-03-05"
......
--- ---
id: 17 id: 17
blogTitle: "How to Start a Blog: A Step-by-Step Guide" title: "How to Start a Blog: A Step-by-Step Guide"
authorDetails: authorDetails:
author: "Mia Harris" author: "Mia Harris"
date: "2022-04-20" date: "2022-04-20"
......
--- ---
id: 18 id: 18
blogTitle: "Remote Work: Tips for Staying Productive" title: "Remote Work: Tips for Staying Productive"
authorDetails: authorDetails:
author: "Isabella Walker" author: "Isabella Walker"
date: "2022-05-15" date: "2022-05-15"
......
--- ---
id: 19 id: 19
blogTitle: "Architectural Wonders Around the World" title: "Architectural Wonders Around the World"
authorDetails: authorDetails:
author: "Isabella Walker" author: "Isabella Walker"
date: "2022-05-15" date: "2022-05-15"
......
--- ---
id: 20 id: 20
blogTitle: "The Future of Air Travel" title: "The Future of Air Travel"
authorDetails: authorDetails:
author: "Matthew Taylor" author: "Matthew Taylor"
date: "2022-06-30" date: "2022-06-30"
......
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