Skip to content

Commit

Permalink
Frontend API Call Strategy updated ⚡
Browse files Browse the repository at this point in the history
  • Loading branch information
NumanIbnMazid committed Aug 28, 2024
1 parent d00b20d commit 1f65653
Show file tree
Hide file tree
Showing 40 changed files with 1,202 additions and 759 deletions.
57 changes: 37 additions & 20 deletions frontend/components/BlogComment/CommentForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { FadeContainer, mobileNavItemSideways } from '@content/FramerMotionVaria
import Ripples from 'react-ripples'
import { useRef } from 'react'
import { CommentInput } from '@lib/types'
import { addBlogComment } from '@lib/backendAPI'

export default function CommentForm({ slug, contentURL }: { slug: string; contentURL: string }) {
const { isDarkMode } = useDarkMode()
Expand Down Expand Up @@ -43,32 +42,50 @@ export default function CommentForm({ slug, contentURL }: { slug: string; conten
// Creating a loading toast
const toastId = toast.loading('Processing ⌛')

const addBlogComment = async (name: string, email: string, comment: string, slug: string) => {
try {
const response = await fetch(`/api/blogs/comments?name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}&comment=${encodeURIComponent(comment)}&slug=${encodeURIComponent(slug)}&method=${encodeURIComponent("POST")}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
return response
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

await addBlogComment(commentData.name, commentData.email, commentData.comment, slug)
.then(() => {
formRef.current.reset()
toast.update(toastId, {
render: 'Thanks for your valuable comment! Your comment will be visible after admin approval.',
type: 'success',
isLoading: false,
autoClose: 7000,
})
sendButtonRef.current.removeAttribute('disabled')
.then(async (response) => {
if (response && response.status === 200) {
formRef.current.reset();
toast.update(toastId, {
render: 'Thanks for your valuable comment! Your comment will be visible after admin approval.',
type: 'success',
isLoading: false,
autoClose: 7000,
})
sendButtonRef.current.removeAttribute('disabled')

// Send email to admin
emailjs.send(
process.env.EMAIL_JS_SERVICE_ID!,
process.env.EMAIL_JS_COMMENT_TEMPLATE_ID!,
commentData!,
process.env.EMAIL_JS_PUBLIC_KEY
)
// Send email to admin
await emailjs.send(
process.env.EMAIL_JS_SERVICE_ID!,
process.env.EMAIL_JS_COMMENT_TEMPLATE_ID!,
commentData!,
process.env.EMAIL_JS_PUBLIC_KEY!
)
} else {
throw new Error('Failed to add comment')
}
})
.catch((err) => {
toast.update(toastId, {
render: '😢 ' + err.text,
render: '😢 ' + err.message, // Updated to err.message
type: 'error',
isLoading: false,
autoClose: false,
})
autoClose: 7000,
});
sendButtonRef.current.removeAttribute('disabled')
})
}
Expand Down
12 changes: 9 additions & 3 deletions frontend/components/BlogComment/CommentList.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react'
import { getAllBlogComments } from '@lib/backendAPI'
import { CommentType } from '@lib/types'
import { useEffect, useState } from 'react'
import Loader from '@components/Loader'
Expand All @@ -11,10 +10,17 @@ const CommentList = ({ slug }: { slug: string }) => {

const fetchBlogCommentList = async (slug: any) => {
try {
const blogCommentData: CommentType[] = await getAllBlogComments(slug)
const response = await fetch(`/api/blogs/comments?name=${encodeURIComponent("")}&email=${encodeURIComponent("")}&comment=${encodeURIComponent("")}&slug=${encodeURIComponent(slug)}&method=${encodeURIComponent("GET")}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
// Parse the JSON body
const blogCommentData: CommentType[] = await response.json()
setComments(blogCommentData)
} catch (error) {
// Handle error case
// Handle errors
console.error('Fetch error:', error)
}
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/components/Home/SkillSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default function SkillSection({ skills, showHomeHeading = true }: { skill
src={skill.image}
alt={skill.title}
quality={50}
layout="fill"
fill
objectFit="contain"
/>
</div>
Expand Down
31 changes: 16 additions & 15 deletions frontend/components/Newsletter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,31 @@ import { ToastContainer, toast } from "react-toastify"
import 'react-toastify/dist/ReactToastify.css'
import { AiOutlineSend } from "react-icons/ai"
import { useDarkMode } from "@context/darkModeContext"
import { subscribeToNewsletter } from "@lib/backendAPI"

export default function Newsletter() {
const { isDarkMode } = useDarkMode()
const [email, setEmail] = useState("")

async function subscribeNewsLetter(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()

const subscribeToNewsLetter = async (email: string) => {
try {
toast.info('Please wait ...')
const response = await fetch(`/api/newsletter-subscribe?email=${encodeURIComponent(email)}`)

const newsLetterSubscriptionResponse = await subscribeToNewsletter(email)
if (!response.ok) {
toast.error("Failed to subscribe nim23's newsletter!")
throw new Error(`HTTP error! Status: ${response.status}`)
}
toast.success("You have successfully subscribed to nim23's newsletter!")
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

// Dismiss the previous toast
toast.dismiss()
async function subscribeNewsLetter(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()

if (newsLetterSubscriptionResponse.success === false) {
toast.error(newsLetterSubscriptionResponse.error.error_details)
} else if (newsLetterSubscriptionResponse.success === true) {
toast.success(newsLetterSubscriptionResponse.message)
} else {
toast.error('Something went wrong. Please try again later.')
}
try {
await subscribeToNewsLetter(email)
} catch (error) {
toast.error('Something went wrong. Please try again later.')
}
Expand Down
32 changes: 17 additions & 15 deletions frontend/components/NewsletterSmall.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,32 @@ import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import { AiOutlineSend } from 'react-icons/ai'
import { useDarkMode } from '@context/darkModeContext'
import { subscribeToNewsletter } from '@lib/backendAPI'


export default function Newsletter() {
const { isDarkMode } = useDarkMode()
const [email, setEmail] = useState('')

async function subscribeNewsLetter(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()

const subscribeToNewsLetter = async (email: string) => {
try {
toast.info('Please wait ...')
const response = await fetch(`/api/newsletter-subscribe?email=${encodeURIComponent(email)}`)

const newsLetterSubscriptionResponse = await subscribeToNewsletter(email)
if (!response.ok) {
toast.error("Failed to subscribe nim23's newsletter!")
throw new Error(`HTTP error! Status: ${response.status}`)
}
toast.success("You have successfully subscribed to nim23's newsletter!")
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

// Dismiss the previous toast
toast.dismiss()
async function subscribeNewsLetter(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()

if (newsLetterSubscriptionResponse.success === false) {
toast.error(newsLetterSubscriptionResponse.error.error_details)
} else if (newsLetterSubscriptionResponse.success === true) {
toast.success(newsLetterSubscriptionResponse.message)
} else {
toast.error('Something went wrong. Please try again later.')
}
try {
await subscribeToNewsLetter(email)
} catch (error) {
toast.error('Something went wrong. Please try again later.')
}
Expand Down
57 changes: 37 additions & 20 deletions frontend/components/SnippetComment/CommentForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { FadeContainer, mobileNavItemSideways } from '@content/FramerMotionVaria
import Ripples from 'react-ripples'
import { useRef } from 'react'
import { CommentInput } from '@lib/types'
import { addSnippetComment } from '@lib/backendAPI'

export default function CommentForm({ slug, contentURL }: { slug: string; contentURL: string }) {
const { isDarkMode } = useDarkMode()
Expand Down Expand Up @@ -43,32 +42,50 @@ export default function CommentForm({ slug, contentURL }: { slug: string; conten
// Creating a loading toast
const toastId = toast.loading('Processing ⌛')

const addSnippetComment = async (name: string, email: string, comment: string, slug: string) => {
try {
const response = await fetch(`/api/snippets/comments?name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}&comment=${encodeURIComponent(comment)}&slug=${encodeURIComponent(slug)}&method=${encodeURIComponent("POST")}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
return response
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

await addSnippetComment(commentData.name, commentData.email, commentData.comment, slug)
.then(() => {
formRef.current.reset()
toast.update(toastId, {
render: 'Thanks for your valuable comment! Your comment will be visible after admin approval.',
type: 'success',
isLoading: false,
autoClose: 7000,
})
sendButtonRef.current.removeAttribute('disabled')
.then(async (response) => {
if (response && response.status === 200) {
formRef.current.reset();
toast.update(toastId, {
render: 'Thanks for your valuable comment! Your comment will be visible after admin approval.',
type: 'success',
isLoading: false,
autoClose: 7000,
})
sendButtonRef.current.removeAttribute('disabled')

// Send email to admin
emailjs.send(
process.env.EMAIL_JS_SERVICE_ID!,
process.env.EMAIL_JS_COMMENT_TEMPLATE_ID!,
commentData!,
process.env.EMAIL_JS_PUBLIC_KEY
)
// Send email to admin
await emailjs.send(
process.env.EMAIL_JS_SERVICE_ID!,
process.env.EMAIL_JS_COMMENT_TEMPLATE_ID!,
commentData!,
process.env.EMAIL_JS_PUBLIC_KEY!
)
} else {
throw new Error('Failed to add comment')
}
})
.catch((err) => {
toast.update(toastId, {
render: '😢 ' + err.text,
render: '😢 ' + err.message, // Updated to err.message
type: 'error',
isLoading: false,
autoClose: false,
})
autoClose: 7000,
});
sendButtonRef.current.removeAttribute('disabled')
})
}
Expand Down
12 changes: 9 additions & 3 deletions frontend/components/SnippetComment/CommentList.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react'
import { getAllSnippetComments } from '@lib/backendAPI'
import { CommentType } from '@lib/types'
import { useEffect, useState } from 'react'
import Loader from '@components/Loader'
Expand All @@ -11,10 +10,17 @@ const CommentList = ({ slug }: { slug: string }) => {

const fetchSnippetCommentList = async (slug: any) => {
try {
const snippetCommentData: CommentType[] = await getAllSnippetComments(slug)
const response = await fetch(`/api/snippets/comments?name=${encodeURIComponent("")}&email=${encodeURIComponent("")}&comment=${encodeURIComponent("")}&slug=${encodeURIComponent(slug)}&method=${encodeURIComponent("GET")}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
// Parse the JSON body
const snippetCommentData: CommentType[] = await response.json()
setComments(snippetCommentData)
} catch (error) {
// Handle error case
// Handle errors
console.error('Fetch error:', error)
}
}

Expand Down
31 changes: 26 additions & 5 deletions frontend/layout/BlogLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import CommentSection from '@components/BlogComment/CommentSection'
import CommentList from '@components/BlogComment/CommentList'
import { AiFillEye, AiFillLike, AiOutlineLike } from 'react-icons/ai'
import useWindowSize from '@hooks/useWindowSize'
import { addBlogLike, addBlogViews } from '@lib/backendAPI'
import { useClientID } from '@context/clientIdContext'
import { getOrSetClientID } from '@lib/clientIDManager'

Expand All @@ -43,13 +42,35 @@ export default function BlogLayout({
const { clientID } = useClientID()

const addLike = async (slug: string) => {
const likeStatusData: LikeStatusType = await addBlogLike(filteredClientID, slug)
setLikeStatus(likeStatusData)
try {
const response = await fetch(`/api/blogs/likes?slug=${encodeURIComponent(slug)}&clientID=${encodeURIComponent(filteredClientID)}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
// Parse the JSON body
const likeStatusData: LikeStatusType = await response.json()
setLikeStatus(likeStatusData)
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

const fetchTotalViews = async (slug: string, finalClientID: string) => {
const totalViewsData: ViewsType = await addBlogViews(finalClientID, slug)
setTotalViews(totalViewsData.total_views)
try {
const response = await fetch(`/api/blogs/views?slug=${encodeURIComponent(slug)}&clientID=${encodeURIComponent(finalClientID)}`)

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
// Parse the JSON body
const totalViewsData: ViewsType = await response.json()
setTotalViews(totalViewsData.total_views)
} catch (error) {
// Handle errors
console.error('Fetch error:', error)
}
}

let readingTime = null
Expand Down
Loading

0 comments on commit 1f65653

Please sign in to comment.