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
import { getAllPosts } from '@/lib/posts';
import { NextResponse } from 'next/server';
import { getAllPosts } from '@/lib/posts';
export async function GET() {
const Data = getAllPosts();
return NextResponse.json({ Data });
const Data = getAllPosts(); // Fetch your data here
// 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';
import { pageData } from "@/utils/Data";
import axios from "axios";
import React, { useEffect } from "react";
import { createContext,useState } from "react";
......@@ -8,7 +7,7 @@ type ContextType= {
ToggleTheme: () => void;
data:{
id: number;
blogTitle: string;
title: string;
authorDetails: {
author: string;
date: Date;
......@@ -31,6 +30,7 @@ type ContextType= {
size: number;
currentPage: number;
handleChangePage: (page: number) => void;
isLoading:boolean
}
export const Context = createContext<ContextType>({
start: 1,
......@@ -38,10 +38,11 @@ export const Context = createContext<ContextType>({
size: 1,
currentPage: 1,
handleChangePage: () => { },
data: pageData,
data: [],
handleFilter: () => { },
theme: 'dark',
ToggleTheme:()=>{}
ToggleTheme: () => { },
isLoading: false
})
interface AppContextProps{
children: React.ReactNode
......@@ -61,17 +62,20 @@ const AppContext = ({ children }: AppContextProps) => {
setstart((page - 1) * size);
setend(page * size);
}
const [filter, setFilter] = useState<any>([]);
const [pageData, setPageData] = useState<any>([]);
const [filter, setFilter] = useState([]);
const [pageData, setPageData] = useState([]);
const [isLoading, setisLoading] = useState(false);
// Fetch data from API and set state
useEffect(() => {
const fetchData = async () => {
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);
setFilter(res.data.Data); // Set filter with fetched data
} catch (error) {
setisLoading(false);
} catch (error) {
setisLoading(false);
console.error("Error fetching data:", error);
}
};
......@@ -80,13 +84,14 @@ const AppContext = ({ children }: AppContextProps) => {
}, []);
// Handle filtering of data based on search input
const handleFilter = (search:string) => {
const handleFilter = (search: string) => {
if (search.trim() === "") {
setFilter(pageData);
} else {
setFilter(
pageData.filter((data:any) =>
data.blogTitle.toLowerCase().includes(search.toLowerCase())
data.title.toLowerCase().includes(search.toLowerCase())
)
);
}
......@@ -101,6 +106,7 @@ const AppContext = ({ children }: AppContextProps) => {
size,
currentPage,
handleChangePage,
isLoading
}}>
{children}
</Context.Provider> );
......
module.exports = {
images: {
domains:['cdn.pixabay.com','images.pexels.com'],
......@@ -26,10 +28,24 @@ module.exports = {
return [
{
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,
compress: false,
};
'use client'
import Heading from "@/components/base/Heading/Heading";
import Loader from "@/components/base/loader/Loader";
import BlogCard from "@/components/Top-Level/blog-card/BlogCard";
import Pagination from "@/components/Top-Level/pagination/pagination";
import { Context } from "@/hooks/AppContext";
......@@ -9,7 +10,7 @@ import { useContext, useEffect, useState } from "react";
const Home = () => {
const [isMounted, setisMounted] = useState(false)
const router = useRouter();
const {data, size, currentPage, start, end, handleChangePage } = useContext(Context);
const {data, size, currentPage, start, end, handleChangePage,isLoading } = useContext(Context);
useEffect(() => {
setisMounted(true);
}, [])
......@@ -17,23 +18,24 @@ const Home = () => {
if (!isMounted) {
return null
}
console.log(data)
return (
<div className="max-w-[1100px] mx-auto px-4 ">
<Heading />
<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) => (
<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">
<BlogCard {
...{
title: data.blogTitle,
img: data.banner.img,
...data.authorDetails,
date:new Date(data.authorDetails.date),
date:new Date(data?.authorDetails.date),
...data,
}
} handleClick={() => {
......@@ -43,8 +45,7 @@ const Home = () => {
))}
</div>
<center className="w-full p-2 sm:p-4 md:p-6 flex justify-center ">
<Pagination size={Math.ceil(data
.length / size)} onChange={handleChangePage} currentPage={currentPage} />
<Pagination size={Math.ceil(data?.length / size)} onChange={handleChangePage} currentPage={currentPage} />
</center>
</div >
......
......@@ -33,7 +33,7 @@ interface BlogData {
}
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;
console.log(data)
const blogData = data.find(item => item.id === id);
......
---
id: 11
blogTitle: "The Ultimate Guide to Adventure Travel"
title: "The Ultimate Guide to Adventure Travel"
authorDetails:
author: "Jane Smith"
date: "2021-01-15"
......
---
id: 12
blogTitle: "10 Must-Visit Destinations in Africa"
title: "10 Must-Visit Destinations in Africa"
authorDetails:
author: "Alex Johnson"
date: "2021-05-10"
......
---
id: 13
blogTitle: "Boost Your Productivity with These Office Hacks"
title: "Boost Your Productivity with These Office Hacks"
authorDetails:
author: "Emily Davis"
date: "2021-07-21"
......
---
id: 14
blogTitle: "Healthy Eating: 7 Delicious Salad Recipes"
title: "Healthy Eating: 7 Delicious Salad Recipes"
authorDetails:
author: "Michael Lee"
date: "2021-08-30"
......
---
id: 15
blogTitle: "Top Hiking Trails for Beginners"
title: "Top Hiking Trails for Beginners"
authorDetails:
author: "Sophia Martinez"
date: "2022-01-20"
......
---
id: 16
blogTitle: "Understanding Asynchronous JavaScript"
title: "Understanding Asynchronous JavaScript"
authorDetails:
author: "David Robinson"
date: "2022-03-05"
......
---
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:
author: "Mia Harris"
date: "2022-04-20"
......
---
id: 18
blogTitle: "Remote Work: Tips for Staying Productive"
title: "Remote Work: Tips for Staying Productive"
authorDetails:
author: "Isabella Walker"
date: "2022-05-15"
......
---
id: 19
blogTitle: "Architectural Wonders Around the World"
title: "Architectural Wonders Around the World"
authorDetails:
author: "Isabella Walker"
date: "2022-05-15"
......
---
id: 20
blogTitle: "The Future of Air Travel"
title: "The Future of Air Travel"
authorDetails:
author: "Matthew Taylor"
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