Skip to content

Commit

Permalink
Added toggle to switch to switch between normal and anonymous questio…
Browse files Browse the repository at this point in the history
…ns and also implemented lazy loading for profile page
  • Loading branch information
auraticabhi committed Mar 6, 2024
1 parent bd9d6a6 commit f97a88a
Show file tree
Hide file tree
Showing 2 changed files with 193 additions and 18 deletions.
187 changes: 169 additions & 18 deletions app/profilePage/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import { useRouter } from 'next/navigation';

import { auth , db } from '@/utils/firebase'
import { useAuthState } from 'react-firebase-hooks/auth'
import { collection, query , where , onSnapshot, orderBy} from 'firebase/firestore';
import { collection, query , where , onSnapshot, orderBy, and, startAfter, limit, getDocs} from 'firebase/firestore';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import Post from '@/components/Post';
import Loader from '@/components/ui/Loader';
import { Button } from '@/components/ui/button';



Expand All @@ -36,30 +38,165 @@ const ProfilePage = (props: Props) => {
const router = useRouter();
const [user, loading] = useAuthState(auth);
// console.log(user);
const [postType, setPostType] = useState("normal");
const [isAnonymous, setIsAnonymous] = useState(false);
const [questions, setQuestions] = useState<PostType[]>([]);
const [anonymousQuestions, setAnonymousQuestions] = useState<PostType[]>([]);
const [loadingPosts, setLoadingPosts] = useState(true);
const [LastDoc, setLastDoc] = useState<any>(null);
const [anonymousMorePosts, setAnonymousMorePosts] = useState(false);
const [anonymousLastdoc, setAnonymousLastdoc] = useState<any>(null);
const [start, setStart] = useState<boolean>(true);
const [anonymousStart, setAnonymousStart] = useState<boolean>(true);
const [morePosts, setMorePosts] = useState(false);

const [loadMore, setLoadMore] = useState<boolean>(false);

useEffect(() => {
if (!user) {
router.push('/auth');
} else {
const questionsRef = collection(db, 'questions');
const q = query(questionsRef, where('uid', '==', user.uid), orderBy('createdAt', 'desc'));
const unsub = onSnapshot(q, (snapshot) => {
setQuestions(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as PostType)));
});
const fetchData = async () => {
try {
if (!user) {
router.push('/auth');
} else {
setLoadingPosts(true);
const questionsRef = collection(db, 'questions');
let q;

if (postType === 'normal') {
if(start){
q = query(questionsRef, and(where('uid', '==', user.uid),
where('anonymity', '==', false)), orderBy('createdAt', 'desc'), limit(7));
const snapshot = await getDocs(q);
setQuestions(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as PostType)));
const lastdoc = snapshot.docs[snapshot.docs.length - 1];
if(lastdoc)setMorePosts(true);
else setMorePosts(false);
setLastDoc(lastdoc);
setStart(false);
}
else{
const moreQ = query(
questionsRef,
and(where('uid', '==', user.uid),
where('anonymity', '==', false)),
orderBy('createdAt', 'desc'),
startAfter(LastDoc),
limit(7)
);

const moreSnapshot = await getDocs(moreQ);
setQuestions((prevQuestions) => [
...prevQuestions,
...moreSnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as PostType)),
]);
const lastdoc = moreSnapshot.docs[moreSnapshot.docs.length - 1];
if(lastdoc)setMorePosts(true);
else setMorePosts(false);
setLastDoc(lastdoc);
}
} else {
if(anonymousStart){
q = query(
questionsRef,
and(where('uid', '==', user.uid),
where('anonymity', '==', true)),
orderBy('createdAt', 'desc'),
limit(7)
);
const snapshot = await getDocs(q);
setAnonymousQuestions(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as PostType)));
const lastdoc = snapshot.docs[snapshot.docs.length - 1];
if(lastdoc)setAnonymousMorePosts(true);
else setAnonymousMorePosts(false);
setAnonymousLastdoc(lastdoc);
setAnonymousStart(false);
}
else{
const moreQ = query(
questionsRef,
and(where('uid', '==', user.uid),
where('anonymity', '==', true)),
orderBy('createdAt', 'desc'),
startAfter(anonymousLastdoc),
limit(7)
);

return () => {
unsub();
const moreSnapshot = await getDocs(moreQ);
setAnonymousQuestions((prevQuestions) => [
...prevQuestions,
...moreSnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as PostType)),
]);
const lastdoc = moreSnapshot.docs[moreSnapshot.docs.length - 1];
if(lastdoc)setAnonymousMorePosts(true);
else setAnonymousMorePosts(false);
setAnonymousLastdoc(lastdoc);
}
};

}
setLoadingPosts(false);
} catch (error) {
console.error('Error fetching data:', error);
setLoadingPosts(false);
}
}
}, [user, loading, router]);
};

fetchData();
}, [user, loading, router, postType, loadMore]);

const handleToggleSwitch = () => {
setStart(true);
setAnonymousStart(true);
setIsAnonymous((prevIsAnonymous) => !prevIsAnonymous);
setPostType((prevPostType) => {
if(prevPostType=='normal')return 'anonymous'
else return 'normal'
});
};

const handleLoadMore = () => {
setLoadMore((prev)=>!prev)
};

console.log("LastDoc ", LastDoc);

return (
<div className=' mt-4'>
<ProfileCard user={user}/>

{(questions?.length === 0) ? (
<div className=' absolute -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 '>
<div className='toggleSwitch flex items-center justify-center mt-5'>
<label className="inline-flex items-center cursor-pointer">
<input type='checkbox' checked={isAnonymous} onChange={handleToggleSwitch} className="sr-only peer"/>
<div className="relative w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
<span className="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300">{isAnonymous ? 'Anonymous Posts' : 'Normal Posts'}</span>
</label>
</div>
<div>
{
<div>{
isAnonymous?<div>{
(anonymousQuestions?.length === 0) ? (
!loadingPosts&&<div className=' absolute -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 '>
<Image
src='/trash.png'
width={300}
height={300}
className=" w-[10rem] h-[9rem] rounded-full"
alt="Profile Pic"
/>
<h1 className=' text-2xl text-zinc-500'>No posts yet</h1>
</div>
) : (
anonymousQuestions &&
anonymousQuestions.map((post, index) => (
// <Post key={index} post={post} />
<div key={index} className=' my-7'>
<Post post={post} />
</div>
))
)}
</div>:
(questions?.length === 0) ? (
!loadingPosts&&<div className=' absolute -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 '>
<Image
src='/trash.png'
width={300}
Expand All @@ -77,8 +214,22 @@ const ProfilePage = (props: Props) => {
<Post post={post} />
</div>
))
)}

)
}
</div>
}
</div>
<div className='flex items-center justify-center'>
{
loadingPosts?<div><Loader/></div>:
<div>
{isAnonymous?
anonymousMorePosts?<Button onClick={handleLoadMore}>LoadMore...</Button>:<div>No More Posts...</div>:morePosts?<Button onClick={handleLoadMore}>LoadMore</Button>
:<div>No More Posts...</div>
}
</div>
}
</div>
<div>
<button onClick={() => auth.signOut()} className="font-medium bg-red-600 hover:bg-red-900 text-white py-2 px-4 rounded-lg textx-sm my-7">Sign Out</button>
</div>
Expand Down
24 changes: 24 additions & 0 deletions components/ui/Loader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React from 'react';

interface LoaderProps {
size?: string;
color?: string;
}

const Loader: React.FC<LoaderProps> = ({ size = '24px', color = '#000000' }) => {
return (
<div className="mt-4 w-full items-center justify-center">

<div role="status">
<svg aria-hidden="true" className="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
</svg>
<span className="sr-only">Loading...</span>
</div>

</div>
);
};

export default Loader;

0 comments on commit f97a88a

Please sign in to comment.