From 60f9733be23366622ee8d131853903026c53b149 Mon Sep 17 00:00:00 2001 From: Akash Singh Date: Wed, 8 May 2024 19:06:20 +0530 Subject: [PATCH] Fixed GraphQL API calls Signed-off-by: Akash Singh --- frontend/app/blogs/[blogid]/page.tsx | 177 +++++++++++++-------------- frontend/app/layout.tsx | 8 +- 2 files changed, 85 insertions(+), 100 deletions(-) diff --git a/frontend/app/blogs/[blogid]/page.tsx b/frontend/app/blogs/[blogid]/page.tsx index 952d4de..561875d 100644 --- a/frontend/app/blogs/[blogid]/page.tsx +++ b/frontend/app/blogs/[blogid]/page.tsx @@ -1,111 +1,107 @@ 'use client' import React, { useEffect, useState } from 'react'; import Header from '../../components/Header'; -import { usePathname } from 'next/navigation'; -import Comments from '../../components/Comments'; -import CommentForm from '../../components/CommentForm'; -import Markdown from 'react-markdown'; +import { usePathname } from 'next/navigation' +import Comments from '../../components/Comments' +import CommentForm from '../../components/CommentForm' +import Markdown from 'react-markdown' import Likes from '@/app/components/Likes'; -import DeleteDialogueBox from '../../components/DeleteDialogueBox'; -import { auth } from '../../firebase'; -import { onAuthStateChanged } from 'firebase/auth'; -import { useQuery, gql } from '@apollo/client'; +import DeleteDialogueBox from "../../components/DeleteDialogueBox"; +import { auth } from "../../firebase"; +import { onAuthStateChanged } from "firebase/auth"; import SpotifyCard from '@/app/components/SpotifyCard'; -//REST API URL const usersAPI = process.env.NEXT_PUBLIC_USERS_API_URL; +const blogsAPI = process.env.NEXT_PUBLIC_BLOGS_API_URL; -//GraphQL queries -const GET_BLOG_BY_ID = gql` - query GetBlogById($blogId: ID!) { - blogPost(BlogID: $blogId) { - id - title - content - created_at - subtitle - image - uploadedImageLink - spotifyLink - user { - id - username - } - } - } -`; - -const GET_USER_BY_ID = gql` - query GetUserById($userId: ID!) { - user(UserID: $userId) { - id - username - } - } -`; - +const formatDate = (timestamp: string): string => { + const date = new Date(timestamp); + const day = date.getDate(); + const month = date.toLocaleString("default", { month: "short" }); + const year = date.getFullYear().toString().slice(-2); + return `${day} ${month} ${year}`; +}; +const getUserById = async (id: number) => { + const response = await fetch(`${usersAPI}/users/${id}`); + const data = await response.json(); + return data; +} const Page = () => { const [isVisibleLikes, setIsVisibleLikes] = useState(true); const [isVisibleDeleteButton, setIsVisibleDeleteButton] = useState(true); const [isVisibleCommentsSection, setIsVisibleCommentsSection] = useState(true); const [loggedInUserId, setLoggedInUserId] = useState(null); - const [isVisible, setIsVisible] = useState(false); - const pathname = usePathname(); - const blogid = pathname.split('/').pop(); - - // Fetch blog post data - const { loading: blogLoading, error: blogError, data: blogData } = useQuery(GET_BLOG_BY_ID, { - variables: { blogId: blogid }, - }); - - // Fetch user data - const { loading: userLoading, error: userError, data: userData } = useQuery(GET_USER_BY_ID, { - variables: { userId: blogData?.blogPost?.user?.id }, - }); - + useEffect(() => { onAuthStateChanged(auth, async (user) => { if (!user) { setIsVisibleLikes(false); setIsVisibleDeleteButton(false); setIsVisibleCommentsSection(false); - } else { - console.log('User logged in successfully'); - try { - const userEmail = user.email; - const userIdResponse = await fetch(`${usersAPI}/users/email/${userEmail}`); - const userIdData = await userIdResponse.json(); - const userid = userIdData.ID; - setLoggedInUserId(userid); - setIsVisibleLikes(true); - setIsVisibleDeleteButton(true); - setIsVisibleCommentsSection(true); - } catch (error) { - console.error(error); - } } + else{ + console.log("User logged in successfully"); + try{ + const userEmail = user.email; + const userId = await fetch(`${usersAPI}/users/email/${userEmail}`, { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }); + const data = await userId.json(); + const userid = data.ID; + setLoggedInUserId(userid); + + setIsVisibleLikes(true); + setIsVisibleDeleteButton(true); + setIsVisibleCommentsSection(true); + } catch (error) { + console.error(error); + } + } }); - }, [auth]); - - if (blogLoading || userLoading) return
Loading...
; - if (blogError || userError) return
Error: {blogError && blogError.message || userError && userError.message}
; - - const blog = blogData.blogPost; - const user = userData.user; + } , [auth]) + + const pathname = usePathname(); + const blogid = pathname.split('/').pop(); + const [blog, setBlog] = useState(null); + const [user, setUser] = useState(null); + const [userId, setUserId] = useState(null); + const [isVisible, setIsVisible] = useState(false); - // Function to open delete dialogue const openDelete = () => { setIsVisible(true); - }; + } - // Format date function - const formatDate = (timestamp : any) => { - const date = new Date(timestamp); - const day = date.getDate(); - const month = date.toLocaleString('default', { month: 'short' }); - const year = date.getFullYear().toString().slice(-2); - return `${day} ${month} ${year}`; - }; + useEffect(() => { + const fetchBlog = async () => { + try { + const response = await fetch(`${blogsAPI}/blogs/${blogid}`); + if (!response.ok) { + throw new Error('Failed to fetch blog'); + } + const data = await response.json(); + console.log("Blog data", data) + setBlog(data); + setUserId(data.user_id); + const user = await getUserById(data.user_id); + setUser(user); + } catch (error) { + console.error(error); + } + }; + + if (blogid) { + fetchBlog(); + } + }, [blogid]); + + if (!blog) { + return
+
+
; + } const formattedDate = formatDate(blog.created_at); @@ -113,22 +109,16 @@ const Page = () => {
- {blog.content} + {blog.content} {isVisible && setIsVisible(false)} />} - {blog.title} + {blog.title}
-

Written By: {user?.username}

+

Written By: {user?.Username}

Published On: {formattedDate}

{isVisibleLikes && } @@ -155,6 +145,7 @@ const Page = () => {
); + }; -export default Page; +export default Page; \ No newline at end of file diff --git a/frontend/app/layout.tsx b/frontend/app/layout.tsx index 646fe92..82d6063 100644 --- a/frontend/app/layout.tsx +++ b/frontend/app/layout.tsx @@ -3,17 +3,13 @@ import { Dosis } from "next/font/google"; import "./globals.css"; import Footer from "./components/Footer"; import { EdgeStoreProvider } from "./lib/edgestore"; -import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; + const dosis = Dosis({ subsets: ["latin"], weight: "600" } ); -const client = new ApolloClient({ - uri: process.env.NEXT_PUBLIC_GRAPHQL_API_URL, - cache: new InMemoryCache() -}); export const metadata: Metadata = { title: "HaalSamachar", @@ -29,11 +25,9 @@ export default function RootLayout({ - {/* */} {children} - {/* */}