Accept request to message
diff --git a/src/components/molecules/CommunityGroupBanner/index.tsx b/src/components/molecules/CommunityGroupBanner/index.tsx
index 86dbb62..a814211 100644
--- a/src/components/molecules/CommunityGroupBanner/index.tsx
+++ b/src/components/molecules/CommunityGroupBanner/index.tsx
@@ -46,7 +46,7 @@ export default function CommunityGroupBanner({ communityID, communityGroupID, is
useEffect(() => {
if (communityGroups && userData) {
- setIsUserJoinedCommunityGroup(communityGroups?.users?.some((user) => user.userId.toString() === userData.id))
+ setIsUserJoinedCommunityGroup(communityGroups?.users?.some((user) => user.userId.toString() === userData?.id))
}
}, [communityGroups])
@@ -162,7 +162,7 @@ export default function CommunityGroupBanner({ communityID, communityGroupID, is
{!communityGroupID ? (
handleCoverImageUpload(e)} />
@@ -173,7 +173,7 @@ export default function CommunityGroupBanner({ communityID, communityGroupID, is
) : (
handleLogoImageUpload(e)} />
@@ -209,7 +209,7 @@ export default function CommunityGroupBanner({ communityID, communityGroupID, is
) : (
{isGroupAdmin ? (
diff --git a/src/components/molecules/CommunityGroupFilter/index.tsx b/src/components/molecules/CommunityGroupFilter/index.tsx
index a22109d..c379c79 100644
--- a/src/components/molecules/CommunityGroupFilter/index.tsx
+++ b/src/components/molecules/CommunityGroupFilter/index.tsx
@@ -9,6 +9,7 @@ const GroupCategories = ['Private', 'Public', 'Official', 'Casual']
type Props = {
communityId: string
+ sort: string
selectedFiltersMain: Record
setSelectedFiltersMain: React.Dispatch>>
selectedTypeMain: string[]
@@ -21,6 +22,7 @@ const CommunityGroupFilterComponent: React.FC = ({
selectedFiltersMain,
setSelectedTypeMain,
selectedTypeMain,
+ sort,
}) => {
const [selectedFilters, setSelectedFilters] = useState>({})
const [selectedType, setSelectedType] = useState([])
@@ -58,9 +60,10 @@ const CommunityGroupFilterComponent: React.FC = ({
}
const handleClick = () => {
- const data = { selectedType, selectedFilters }
+ const data = { selectedType, selectedFilters, sort }
setSelectedFiltersMain(selectedFilters)
setSelectedTypeMain(selectedType)
+
mutate(data)
}
diff --git a/src/components/molecules/MessageNotification/index.tsx b/src/components/molecules/MessageNotification/index.tsx
index ff1530e..745983c 100644
--- a/src/components/molecules/MessageNotification/index.tsx
+++ b/src/components/molecules/MessageNotification/index.tsx
@@ -86,8 +86,8 @@ const MessageNotification = ({ message }: MessageNotificationsProps) => {
{item?.isGroupChat
? item?.chatName
- : `${item?.users?.find((user) => user?.userId._id.toString() !== userData.id)?.userId.firstName || ''} ${
- item?.users?.find((user) => user?.userId._id.toString() !== userData.id)?.userId.lastName || ''
+ : `${item?.users?.find((user) => user?.userId._id.toString() !== userData?.id)?.userId.firstName || ''} ${
+ item?.users?.find((user) => user?.userId._id.toString() !== userData?.id)?.userId.lastName || ''
}`}
diff --git a/src/components/molecules/NavbarUniversityItem/index.tsx b/src/components/molecules/NavbarUniversityItem/index.tsx
index fe8fe77..969e79e 100644
--- a/src/components/molecules/NavbarUniversityItem/index.tsx
+++ b/src/components/molecules/NavbarUniversityItem/index.tsx
@@ -1,7 +1,7 @@
'use client'
import GroupSearchBox from '@/components/atoms/GroupSearchBox'
import UserListItemSkeleton from '@/components/Connections/UserListItemSkeleton'
-import { useGetSubscribedCommunties } from '@/services/university-community'
+import { useGetFilteredSubscribedCommunities, useGetSubscribedCommunties } from '@/services/university-community'
import Image from 'next/image'
import { useParams, useRouter } from 'next/navigation'
import React, { useEffect, useMemo, useState } from 'react'
@@ -16,6 +16,9 @@ import { Community } from '@/types/Community'
import { openModal } from '../Modal/ModalManager'
import CommunityGroupFilterComponent from '../CommunityGroupFilter'
import Buttons from '@/components/atoms/Buttons'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/Popover'
+import { sortBy } from '@/types/CommuityGroup'
+import useCookie from '@/hooks/useCookie'
interface Props {
setActiveMenu: (activeMenu: string) => void
@@ -24,6 +27,7 @@ interface Props {
export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }: Props) {
const { userData } = useUniStore()
+ const [cookieValue] = useCookie('uni_user_token')
const router = useRouter()
const { communityId, groupId: communityGroupId }: { communityId: string; groupId: string } = useParams()
const [currSelectedGroup, setCurrSelectedGroup] = useState()
@@ -31,11 +35,15 @@ export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }
const [showNewGroup, setShowNewGroup] = useState(false)
const [selectedFiltersMain, setSelectedFiltersMain] = useState>({})
const [selectedTypeMain, setSelectedTypeMain] = useState([])
+ const [sort, setSort] = useState('')
const [assignUsers, setAssignUsers] = useState(false)
const [showGroupTill, setShowGroupTill] = useState(5)
const [community, setCommunity] = useState()
const [selectCommunityId, selectedCommuntyGroupdId] = [communityId || community?._id, communityGroupId]
const { data: subscribedCommunities, isFetching, isLoading } = useGetSubscribedCommunties()
+ // console.log('comm', communityId, 'iii', community?._id)
+
+ const { mutate: mutateFilterCommunityGroups } = useGetFilteredSubscribedCommunities(community?._id)
const handleCommunityClick = (index: number) => {
handleUniversityClick(index)
@@ -58,6 +66,7 @@ export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }
selectedFiltersMain={selectedFiltersMain}
setSelectedTypeMain={setSelectedTypeMain}
selectedTypeMain={selectedTypeMain}
+ sort={sort}
/>
)
}
@@ -83,8 +92,8 @@ export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }
() =>
subscribedCommunities
?.find((community) => community._id === (communityId || subscribedCommunities?.[0]._id))
- ?.communityGroups.filter((communityGroup) => communityGroup.adminUserId === userData.id),
- [subscribedCommunities, communityId, userData.id, community]
+ ?.communityGroups.filter((communityGroup) => communityGroup.adminUserId === userData?.id),
+ [subscribedCommunities, communityId, userData?.id, community]
)
useEffect(() => {
@@ -95,6 +104,14 @@ export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }
}
}, [subscribedCommunities, communityId])
+ //sort
+ useEffect(() => {
+ const data = { selectedType: selectedTypeMain, selectedFilters: selectedFiltersMain, sort }
+ if (cookieValue && community?._id && (selectedFiltersMain?.length || selectedTypeMain?.length || sort.length)) {
+ mutateFilterCommunityGroups(data)
+ }
+ }, [sort, cookieValue, community?._id])
+
const tabData = [
{
label: 'All',
@@ -174,7 +191,7 @@ export default function NavbarUniversityItem({ setActiveMenu, toggleLeftNavbar }
return (
<>
handleCommunityGroupFilter()} size="extra_small" variant="border_primary">
Filter
-
- Sort
-
+
+
+
+ Sort
+
+
+
+
+ {sortBy.map((item) => (
+
setSort(item)} key={item} className="capitalize cursor-pointer">
+ {item}
+
+ ))}
+
+
+
diff --git a/src/components/molecules/NewPostComment/index.tsx b/src/components/molecules/NewPostComment/index.tsx
index bdb582f..f53c627 100644
--- a/src/components/molecules/NewPostComment/index.tsx
+++ b/src/components/molecules/NewPostComment/index.tsx
@@ -45,7 +45,7 @@ const NewPostComment = ({ setNewPost, data, postId, isReply, isNested }: Props)
@@ -213,7 +213,7 @@ const PostCard = ({
-
+
)
}
diff --git a/src/components/molecules/PostCommentBox/index.tsx b/src/components/molecules/PostCommentBox/index.tsx
index 7a19d42..c8fcdb3 100644
--- a/src/components/molecules/PostCommentBox/index.tsx
+++ b/src/components/molecules/PostCommentBox/index.tsx
@@ -395,7 +395,7 @@ const PostCommentBox = ({ showCommentSec, postID, type, data }: Props) => {
{
if (communityData && userData) {
- setIsUserJoinedCommunity(communityData.users.some((user) => user?.id?.toString() === userData.id))
+ setIsUserJoinedCommunity(communityData.users.some((user) => user?.id?.toString() === userData?.id))
}
}, [communityData, userData])
diff --git a/src/components/molecules/UserMessages/index.tsx b/src/components/molecules/UserMessages/index.tsx
index 738904e..f088682 100644
--- a/src/components/molecules/UserMessages/index.tsx
+++ b/src/components/molecules/UserMessages/index.tsx
@@ -211,7 +211,7 @@ const UserMessages = ({ name, profileCover, chatId, users, isRequest, isGroupCha
profilePic={item?.senderProfile?.profile_dp?.imageUrl}
name={item?.sender?.firstName}
content={item?.content}
- myMessage={item?.sender.id === userData.id}
+ myMessage={item?.sender.id === userData?.id}
date={item.createdAt}
id={item?._id}
reactions={item?.reactions}
@@ -226,7 +226,7 @@ const UserMessages = ({ name, profileCover, chatId, users, isRequest, isGroupCha
})}
-
+
)
diff --git a/src/components/organism/MobileViewNavbar/index.tsx b/src/components/organism/MobileViewNavbar/index.tsx
index 28f6c26..d4ecb1b 100644
--- a/src/components/organism/MobileViewNavbar/index.tsx
+++ b/src/components/organism/MobileViewNavbar/index.tsx
@@ -13,6 +13,7 @@ import { HiCubeTransparent } from 'react-icons/hi'
import { TbLogout } from 'react-icons/tb'
import { useRouter } from 'next/navigation'
import useCookie from '@/hooks/useCookie'
+import { useLogout } from '@/hooks/useLogOut'
interface Props {
closeLeftNavbar: () => void
@@ -22,11 +23,11 @@ interface Props {
export default function MobileViewNavbar({ closeLeftNavbar, toggleRightMenu, showRightMenu }: Props) {
const router = useRouter()
- const { userProfileData, userData, resetUserProfileData } = useUniStore()
+ const { userProfileData, userData } = useUniStore()
const [, , deleteCookie] = useCookie('uni_user_token')
-
+ const { handleLogout } = useLogout()
const handleProfileClicked = () => {
- router.push(`/profile/${userData.id}`)
+ router.push(`/profile/${userData?.id}`)
toggleRightMenu()
}
const handleMenuClicked = (path: string) => {
@@ -38,14 +39,9 @@ export default function MobileViewNavbar({ closeLeftNavbar, toggleRightMenu, sho
toggleRightMenu()
closeLeftNavbar()
}
- const handleLogout = () => {
- deleteCookie()
- resetUserProfileData()
- router.push('/login')
- }
const renderProfile = () => {
- if (!userProfileData.profile_dp) {
+ if (!userProfileData?.profile_dp) {
return null
}
if (Object?.keys(userProfileData)?.length === 0) {
@@ -90,12 +86,12 @@ export default function MobileViewNavbar({ closeLeftNavbar, toggleRightMenu, sho
{renderProfile()}
- {userData.firstName} {userData.lastName}
+ {userData?.firstName} {userData?.lastName}
{truncateString(userProfileData?.university_name || '')}
-
{userProfileData.major}
+
{userProfileData?.major}
diff --git a/src/components/organisms/CommunityGroupPostContainer/index.tsx b/src/components/organisms/CommunityGroupPostContainer/index.tsx
index 9c6426e..0ddee19 100644
--- a/src/components/organisms/CommunityGroupPostContainer/index.tsx
+++ b/src/components/organisms/CommunityGroupPostContainer/index.tsx
@@ -4,11 +4,13 @@ import { Skeleton } from '@/components/ui/Skeleton'
import { useGetCommunityGroupPost } from '@/services/community-university'
import { communityPostType } from '@/types/Community'
import { PostType } from '@/types/constants'
+import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'next/navigation'
import React, { useEffect, useRef, useState } from 'react'
function CommunityGroupPostContainer({ containerRef }: { containerRef: any }) {
const { communityId, groupId: communityGroupId }: { communityId: string; groupId: string } = useParams()
+ const queryClient = useQueryClient()
const [imageCarasol, setImageCarasol] = useState<{
isShow: boolean
images: any
@@ -27,8 +29,11 @@ function CommunityGroupPostContainer({ containerRef }: { containerRef: any }) {
hasNextPage: communityPostHasNextPage,
isLoading,
error,
+ isFetching,
+ dataUpdatedAt,
} = useGetCommunityGroupPost(communityId, communityGroupId, true, 2)
- const communityGroupPostData = communityGroupPost?.pages.flatMap((page) => page?.finalPost) || []
+ const [communityGroupPostDatas, setCommunityGroupPostDatas] = useState([])
+ // const communityGroupPostData = communityGroupPost?.pages.flatMap((page) => page?.finalPost) || []
useEffect(() => {
const handleScroll = () => {
@@ -49,16 +54,27 @@ function CommunityGroupPostContainer({ containerRef }: { containerRef: any }) {
}
}, [communityPostHasNextPage, communityPostIsFetchingNextPage, communityPostNextpage])
+ useEffect(() => {
+ if (isFetching) {
+ setCommunityGroupPostDatas([])
+ }
+ }, [isFetching, queryClient])
+
+ useEffect(() => {
+ const communityDatas: any = communityGroupPost?.pages.flatMap((page) => page?.finalPost)
+ setCommunityGroupPostDatas(communityDatas)
+ }, [communityGroupPost, dataUpdatedAt])
+
if (isLoading) return
if (error) {
return
{(error as any)?.response?.data?.message || 'Something went wrong'}
}
- if (communityGroupPostData.length === 0) return
No posts found
+ if (communityGroupPostDatas.length === 0) return
No posts found
return (
- {communityGroupPostData?.map((post: communityPostType, idx: number) => (
+ {communityGroupPostDatas?.map((post: communityPostType, idx: number) => (
{
- router.push(`/profile/${userData.id}`)
+ router.push(`/profile/${userData?.id}`)
setActiveMenu('')
toggleLeftNavbar && toggleLeftNavbar()
}
-
+ // if (userProfileData && Object?.keys(userProfileData)?.length === 0) {
const renderProfile = () => {
- if (!userProfileData.profile_dp) {
+ if (!userProfileData?.profile_dp) {
return null
}
if (Object?.keys(userProfileData)?.length === 0) {
@@ -60,7 +60,7 @@ export default function LeftNavbar({ toggleLeftNavbar }: Props) {
height={50}
objectFit="cover"
className="w-[50px] h-[50px] rounded-full"
- src={userProfileData.profile_dp?.imageUrl || avatar}
+ src={userProfileData?.profile_dp?.imageUrl || avatar}
alt="profile.png"
/>
)
@@ -72,13 +72,13 @@ export default function LeftNavbar({ toggleLeftNavbar }: Props) {
{renderProfile()}
- {userData.firstName} {userData.lastName}
+ {userData?.firstName} {userData?.lastName}
{truncateString(userProfileData?.university_name || '')}
-
{userProfileData.major}
+
{userProfileData?.major}
diff --git a/src/components/organisms/MessageContainer/index.tsx b/src/components/organisms/MessageContainer/index.tsx
index ac924e6..9124d8f 100644
--- a/src/components/organisms/MessageContainer/index.tsx
+++ b/src/components/organisms/MessageContainer/index.tsx
@@ -24,7 +24,7 @@ const MessageContainer = () => {
const [selectedChat, setSelectedChat] = useState
(undefined)
const { userData, socket } = useUniStore()
- const userName = selectedChat?.users?.find((item) => item?.userId._id !== userData.id)
+ const userName = selectedChat?.users?.find((item) => item?.userId._id !== userData?.id)
const queryClient = useQueryClient()
const { mutate: updateIsSeen } = useUpdateMessageIsSeen()
const [isRequest, setIsRequest] = useState(true)
@@ -45,7 +45,7 @@ const MessageContainer = () => {
const unreadChatsCount = chats.filter((item) => {
if (item.isGroupChat) {
- return item.unreadMessagesCount > 0 && item.users.some((user) => user.userId._id == userData.id && user.isRequestAccepted)
+ return item.unreadMessagesCount > 0 && item.users.some((user) => user.userId._id == userData?.id && user.isRequestAccepted)
} else {
return item.unreadMessagesCount > 0 && item.isRequestAccepted
}
@@ -59,10 +59,10 @@ const MessageContainer = () => {
}).length
const updateMessageSeen = () => {
- const isRead = selectedChat?.latestMessage?.readByUsers?.includes(userData.id || '')
+ const isRead = selectedChat?.latestMessage?.readByUsers?.includes(userData?.id || '')
if (!isRead && isRead !== undefined && selectedChat) {
- updateIsSeen({ chatId: selectedChat?._id, messageId: selectedChat?.latestMessage?._id, data: { readByUserId: userData.id } })
+ updateIsSeen({ chatId: selectedChat?._id, messageId: selectedChat?.latestMessage?._id, data: { readByUserId: userData?.id } })
}
}
@@ -107,10 +107,10 @@ const MessageContainer = () => {
)
queryClient.setQueryData(['userChats'], updatedChats)
- const isRead = newMessage?.readByUsers?.includes(userData.id || '')
+ const isRead = newMessage?.readByUsers?.includes(userData?.id || '')
if (!isRead && selectedChat?._id) {
- updateIsSeen({ chatId: selectedChat?._id, messageId: chatMessageId, data: { readByUserId: userData.id } })
+ updateIsSeen({ chatId: selectedChat?._id, messageId: chatMessageId, data: { readByUserId: userData?.id } })
}
} else if (!chatData.some((chat) => chat._id == messageChatId)) {
queryClient.invalidateQueries({ queryKey: ['userChats'] })
@@ -120,9 +120,9 @@ const MessageContainer = () => {
const userChatsId = useMemo(() => {
return chatsData?.flatMap((chat) =>
- chat.users.map((user) => (user.userId._id !== userData.id ? user.userId._id : null)).filter((id) => id !== null)
+ chat.users.map((user) => (user.userId._id !== userData?.id ? user.userId._id : null)).filter((id) => id !== null)
)
- }, [chatsData, userData.id])
+ }, [chatsData, userData?.id])
const uniqUserChatID = useMemo(() => new Set(userChatsId), [userChatsId])
@@ -266,7 +266,7 @@ const MessageContainer = () => {
degree={userName?.userId.degree ?? 'Unknown'}
universitry={userName?.userId.universityName ?? 'Unknown'}
users={selectedChat?.users}
- yourID={userData.id || ''}
+ yourID={userData?.id || ''}
isGroupChat={selectedChat?.isGroupChat}
isRequestNotAccepted={currTab == 'Message Requests'}
chatId={selectedChat?._id}
@@ -282,7 +282,7 @@ const MessageContainer = () => {
profileCover={selectedChat?.groupLogoImage ?? ''}
isRequest={isRequest}
isGroupChat={selectedChat?.isGroupChat}
- yourID={userData.id || ''}
+ yourID={userData?.id || ''}
setImageCarasol={setImageCarasol}
isRequestNotAccepted={currTab == 'Message Requests'}
/>
diff --git a/src/components/organisms/SettingsSection/SettingTabs/SettingAccount.tsx b/src/components/organisms/SettingsSection/SettingTabs/SettingAccount.tsx
index e7d83ee..4578beb 100644
--- a/src/components/organisms/SettingsSection/SettingTabs/SettingAccount.tsx
+++ b/src/components/organisms/SettingsSection/SettingTabs/SettingAccount.tsx
@@ -11,13 +11,26 @@ import Button from '@/components/atoms/Buttons'
import InputBox from '@/components/atoms/Input/InputBox'
import { useUniStore } from '@/store/store'
+import { userProfileType } from '@/store/userProfileSlice/userProfileType'
+import { userType } from '@/store/userSlice/userType'
+
+interface emailType {
+ UniversityName: string
+ UniversityEmail: string
+ communityId: string
+}
type props = {
setModal: (value: string) => void
}
const SettingAccount = ({ setModal }: props) => {
- const { email } = useUniStore((state) => state.userProfileData)
- const { userName, email: userEmail } = useUniStore((state) => state.userData)
+ const userProfileData = useUniStore((state) => state.userProfileData) || { email: [] }
+
+ const email: emailType[] = userProfileData.email || []
+
+ const userData = useUniStore((state) => state.userData) || {}
+ const userName = userData.userName || ''
+ const userEmail = userData.email || ''
return (
@@ -31,7 +44,7 @@ const SettingAccount = ({ setModal }: props) => {
)}
{email?.length ? (
- email?.map((item, idx) => (
+ email?.map((item: emailType, idx) => (
diff --git a/src/components/organisms/UserChats/index.tsx b/src/components/organisms/UserChats/index.tsx
index 0dc9201..9b0d3ac 100644
--- a/src/components/organisms/UserChats/index.tsx
+++ b/src/components/organisms/UserChats/index.tsx
@@ -22,9 +22,9 @@ const UserChats = ({ setSelectedChat, selectedChat, setIsRequest, currTabb, chat
if (currTabb === 'Inbox') {
const filteredChats = chats?.filter(
(item: Chat) =>
- item.users.find((user) => user?.userId._id.toString() === userData.id && user?.isRequestAccepted) ||
+ item.users.find((user) => user?.userId._id.toString() === userData?.id && user?.isRequestAccepted) ||
item.isRequestAccepted ||
- item.groupAdmin.toString() === userData.id
+ item.groupAdmin.toString() === userData?.id
)
if (isChatLoading) {
@@ -41,10 +41,10 @@ const UserChats = ({ setSelectedChat, selectedChat, setIsRequest, currTabb, chat
groupName={item?.chatName}
isGroupChat={item?.isGroupChat}
users={[item?.users]}
- isSeen={item?.latestMessage?.readByUsers?.includes(userData.id || ' ')}
+ isSeen={item?.latestMessage?.readByUsers?.includes(userData?.id || ' ')}
lastMessage={item?.latestMessage?.content}
date={item?.latestMessage?.createdAt && dayjs(new Date(item?.latestMessage?.createdAt).toString()).fromNow()}
- YourID={userData.id}
+ YourID={userData?.id}
unRead={item?.unreadMessagesCount}
/>
@@ -52,8 +52,8 @@ const UserChats = ({ setSelectedChat, selectedChat, setIsRequest, currTabb, chat
} else if (currTabb === 'Message Requests') {
const filteredChats = chats?.filter((item: Chat) =>
item.isGroupChat
- ? item.users.some((user) => user.userId._id.toString() === userData.id && !user.isRequestAccepted)
- : !item.isRequestAccepted && item.groupAdmin.toString() !== userData.id
+ ? item.users.some((user) => user.userId._id.toString() === userData?.id && !user.isRequestAccepted)
+ : !item.isRequestAccepted && item.groupAdmin.toString() !== userData?.id
)
if (filteredChats.length === 0) {
@@ -67,16 +67,16 @@ const UserChats = ({ setSelectedChat, selectedChat, setIsRequest, currTabb, chat
groupName={item?.chatName}
isGroupChat={item?.isGroupChat}
users={[item?.users]}
- isSeen={item?.latestMessage?.readByUsers?.includes(userData.id || ' ')}
+ isSeen={item?.latestMessage?.readByUsers?.includes(userData?.id || ' ')}
lastMessage={item?.latestMessage?.content}
date={item?.latestMessage?.createdAt && dayjs(new Date(item?.latestMessage?.createdAt).toString()).fromNow()}
- YourID={userData.id}
+ YourID={userData?.id}
unRead={item?.unreadMessagesCount}
/>
))
} else {
- const filteredChats = chats?.filter((item: Chat) => item.users.find((user) => user?.userId._id.toString() === userData.id && user?.isStarred))
+ const filteredChats = chats?.filter((item: Chat) => item.users.find((user) => user?.userId._id.toString() === userData?.id && user?.isStarred))
if (filteredChats.length === 0) {
return
You have no starred chats.
@@ -89,10 +89,10 @@ const UserChats = ({ setSelectedChat, selectedChat, setIsRequest, currTabb, chat
groupName={item?.chatName}
isGroupChat={item?.isGroupChat}
users={[item?.users]}
- isSeen={item?.latestMessage?.readByUsers?.includes(userData.id || ' ')}
+ isSeen={item?.latestMessage?.readByUsers?.includes(userData?.id || ' ')}
lastMessage={item?.latestMessage?.content}
date={item?.latestMessage?.createdAt && dayjs(new Date(item?.latestMessage?.createdAt).toString()).fromNow()}
- YourID={userData.id}
+ YourID={userData?.id}
unRead={item?.unreadMessagesCount}
/>
diff --git a/src/hooks/useLogOut.ts b/src/hooks/useLogOut.ts
new file mode 100644
index 0000000..b5c5b5d
--- /dev/null
+++ b/src/hooks/useLogOut.ts
@@ -0,0 +1,21 @@
+import { useRouter } from 'next/navigation'
+import { useUniStore } from '@/store/store'
+import useCookie from './useCookie'
+
+export const useLogout = () => {
+ const router = useRouter()
+ const [, , deleteCookie] = useCookie('uni_user_token')
+ const [, , deleteRefreshCookie] = useCookie('uni_user_refresh_token')
+
+ const handleLogout = () => {
+ deleteCookie()
+ deleteRefreshCookie()
+ useUniStore.getState().reset()
+
+ localStorage.removeItem('store')
+
+ router.push('/login')
+ }
+
+ return { handleLogout }
+}
diff --git a/src/middleware.ts b/src/middleware.ts
index a1439d6..aa52c49 100644
--- a/src/middleware.ts
+++ b/src/middleware.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { isAuthenticated } from './utils/Authentication'
-const protectedRoutes = ['/community', '/timeline', '/:id']
+const protectedRoutes = ['/community', '/timeline', '/profile', '/:id', '/messages', '/notifications', '/ai-assistant', '/setting', '/connections']
export default function middleware(req: NextRequest) {
const pathName = req.nextUrl.pathname
diff --git a/src/services/edit-profile.ts b/src/services/edit-profile.ts
index 6a6f9b5..0a86268 100644
--- a/src/services/edit-profile.ts
+++ b/src/services/edit-profile.ts
@@ -16,7 +16,7 @@ export const useEditProfile = () => {
const setUserProfileData = useUniStore((state) => state.setUserProfileData)
const { userProfileData } = useUniStore()
return useMutation({
- mutationFn: (data: any) => editProfile(data, userProfileData._id || ''),
+ mutationFn: (data: any) => editProfile(data, userProfileData?._id || ''),
onSuccess: (response: any) => {
setUserProfileData(response.updatedUserProfile)
},
diff --git a/src/services/university-community.ts b/src/services/university-community.ts
index 989e1a3..69282f4 100644
--- a/src/services/university-community.ts
+++ b/src/services/university-community.ts
@@ -20,7 +20,7 @@ export function useGetSubscribedCommunties() {
enabled: !!cookieValue,
}) as UseQueryResult
}
-export function useGetFilteredSubscribedCommunities(communityId: string) {
+export function useGetFilteredSubscribedCommunities(communityId: string = '') {
const [cookieValue] = useCookie('uni_user_token')
const queryClient = useQueryClient()
return useMutation({
diff --git a/src/store/store.ts b/src/store/store.ts
index 167a8f6..83f8c05 100644
--- a/src/store/store.ts
+++ b/src/store/store.ts
@@ -5,13 +5,30 @@ import { createUserProfileSlice } from './userProfileSlice/userProfileSlice'
import { createSocketSlice } from './socketSlice/socketSlice'
import { storeType } from './storeType'
+let finalCookie: any = null
+
+if (typeof document !== 'undefined') {
+ const cookieValue = document.cookie.split('; ').find((row) => row.startsWith('uni_user_token='))
+ finalCookie = cookieValue ? cookieValue.split('=')[1] : null
+}
+
export const useUniStore = create()(
devtools(
+ // persist(
+ // (...a) => ({
+ // ...createUserSlice(...a),
+ // ...createUserProfileSlice(...a),
+ // ...createSocketSlice(...a),
+ // }),
persist(
- (...a) => ({
- ...createUserSlice(...a),
- ...createUserProfileSlice(...a),
- ...createSocketSlice(...a),
+ (set, get, api) => ({
+ ...createUserSlice(set, get, api),
+ ...createUserProfileSlice(set, get, api),
+ ...createSocketSlice(set, get, api),
+ reset: () => {
+ set({}, true)
+ api.persist.clearStorage()
+ },
}),
{
name: 'store',
@@ -19,6 +36,7 @@ export const useUniStore = create()(
...state,
socket: undefined, // Exclude socket from persisted state
}),
+ skipHydration: !finalCookie,
// partialize: (state) => ({ products: state.products,userName:state.userName }),
// skipHydration: true
}
diff --git a/src/store/storeType.ts b/src/store/storeType.ts
index 0baa2b8..1c8ce19 100644
--- a/src/store/storeType.ts
+++ b/src/store/storeType.ts
@@ -3,4 +3,9 @@ import { userProfileSlice } from './userProfileSlice/userProfileSlice'
import { SocketSlice } from './socketSlice/socketSlice'
-export type storeType = userSlice & userProfileSlice & SocketSlice
+// export type storeType = userSlice & userProfileSlice & SocketSlice
+export type storeType = userSlice &
+ userProfileSlice &
+ SocketSlice & {
+ reset: () => void
+ }
diff --git a/src/store/userProfileSlice/userProfileSlice.ts b/src/store/userProfileSlice/userProfileSlice.ts
index f55b549..ab3d348 100644
--- a/src/store/userProfileSlice/userProfileSlice.ts
+++ b/src/store/userProfileSlice/userProfileSlice.ts
@@ -2,18 +2,18 @@ import { StateCreator } from 'zustand'
import { userProfileType } from './userProfileType'
type userProfileState = {
- userProfileData: Partial
+ userProfileData: Partial | null
}
type userProfileAction = {
setUserProfileData: (userProfileData: userProfileType) => void
setUserFollowers: (communities: userProfileType['followers']) => void
setUserfollowing: (communities: userProfileType['following']) => void
- resetUserProfileData: () => void
}
const initialState: userProfileState = {
- userProfileData: {},
+ userProfileData: null,
+ // userProfileData: {},
}
export type userProfileSlice = userProfileState & userProfileAction
@@ -35,5 +35,4 @@ export const createUserProfileSlice: StateCreator = (set) => (
following: followings,
},
})),
- resetUserProfileData: () => set(initialState),
})
diff --git a/src/store/userSlice/userSlice.ts b/src/store/userSlice/userSlice.ts
index 290599c..87f20d7 100644
--- a/src/store/userSlice/userSlice.ts
+++ b/src/store/userSlice/userSlice.ts
@@ -2,7 +2,8 @@ import { StateCreator } from 'zustand'
import { userType } from './userType'
type userState = {
- userData: Partial
+ // userData: Partial
+ userData: Partial | null
}
type userAction = {
@@ -13,7 +14,8 @@ type userAction = {
}
const initialState: userState = {
- userData: {},
+ // userData: {},
+ userData: null,
}
export type userSlice = userState & userAction
diff --git a/src/types/CommuityGroup/index.ts b/src/types/CommuityGroup/index.ts
index eb2da28..4c4b7af 100644
--- a/src/types/CommuityGroup/index.ts
+++ b/src/types/CommuityGroup/index.ts
@@ -143,3 +143,5 @@ export const subCategories: Record = {
],
Others: [],
}
+
+export const sortBy = ['name', 'latest', 'users', 'oldest']
diff --git a/src/utils/ZustandSocketProvider.tsx b/src/utils/ZustandSocketProvider.tsx
index 00e7ed8..1afeba5 100644
--- a/src/utils/ZustandSocketProvider.tsx
+++ b/src/utils/ZustandSocketProvider.tsx
@@ -29,16 +29,23 @@ const ZustandSocketProvider: React.FC = ({ children
} = useGetUserProfileData(type)
useEffect(() => {
- if (userData.id) {
+ if (userData?.id) {
const routeSegment = param.split('/')[1]
const isRouteMessage = routeSegment !== 'messages'
- initializeSocket(userData.id, refetchUserData, refetchNotification, refetchUserProfileData, refetchMessageNotification, isRouteMessage)
+ initializeSocket(userData?.id, refetchUserData, refetchNotification, refetchUserProfileData, refetchMessageNotification, isRouteMessage)
}
+ // return () => {
+ // disconnectSocket()
+ // }
return () => {
- disconnectSocket()
+ if (typeof disconnectSocket === 'function') {
+ disconnectSocket()
+ } else {
+ console.warn('disconnectSocket is not defined or not a function')
+ }
}
- }, [userData.id, initializeSocket, disconnectSocket, refetchNotification, param])
+ }, [userData?.id, initializeSocket, disconnectSocket, refetchNotification, param])
useEffect(() => {
if ((refectUserDataIsSuccess && !isFetching) || (refectUserProfileDataIsSuccess && !userProfileRefething)) {