Skip to content

Commit

Permalink
fix: User profile is not opening ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
Nishitbaria committed Sep 12, 2024
1 parent 882a848 commit 29db49d
Show file tree
Hide file tree
Showing 9 changed files with 177 additions and 68 deletions.
31 changes: 31 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-dropzone": "^14.2.3",
"react-error-boundary": "^4.0.13",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.13.1",
"react-router-dom": "^6.26.2",
Expand Down
64 changes: 34 additions & 30 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,45 @@ import Custom404 from './_root/pages/Custom404';
import PrivacyPolicy from './components/shared/PrivacyPolicy';
import Licensing from './components/shared/Licensing';
import TermsandConditions from './components/shared/TermsandConditions';
import ErrorBoundary from './components/shared/ErrorBoundary';


const App = () => {
return (
<main className="flex h-screen">
<Routes>
{/* Public Routes */}
<Route element={<AuthLayout />}>
<Route path="/Homepage" element={<HomePage />} />
<Route path="/sign-in" element={<SigninForm />} />
<Route path="/sign-up" element={<SignupForm />} />
</Route>
<ErrorBoundary>
<main className="flex h-screen">
<Routes>
{/* Public Routes */}
<Route element={<AuthLayout />}>
<Route path="/Homepage" element={<HomePage />} />
<Route path="/sign-in" element={<SigninForm />} />
<Route path="/sign-up" element={<SignupForm />} />
</Route>

{/* Private Routes */}
<Route element={<RootLayout />}>
<Route index element={<Home />} />
<Route path="/Homepage" element={<HomePage />} />
<Route path="/explore" element={<Explore />} />
<Route path="/saved" element={<Saved />} />
<Route path="/all-users" element={<AllUsers />} />
<Route path="/create-post" element={<CreatePost />} />
<Route path="/update-post/:id" element={<EditPost />} />
<Route path="/posts/:id" element={<PostDetails />} />
<Route path="/profile/:id/*" element={<Profile />} />
<Route path="/update-profile/:id" element={<UpdateProfile />} />
<Route path="/settings" element={<Settings />} />
<Route path="/privacypolicy" element={<PrivacyPolicy />} />
<Route path="/licensing" element={<Licensing />} />
<Route path="/termsandconditions" element={<TermsandConditions />} />
</Route>
{/* Private Routes */}
<Route element={<RootLayout />}>
<Route index element={<Home />} />
<Route path="/Homepage" element={<HomePage />} />
<Route path="/explore" element={<Explore />} />
<Route path="/saved" element={<Saved />} />
<Route path="/all-users" element={<AllUsers />} />
<Route path="/create-post" element={<CreatePost />} />
<Route path="/update-post/:id" element={<EditPost />} />
<Route path="/posts/:id" element={<PostDetails />} />
<Route path="/profile/:id/*" element={<Profile />} />
<Route path="/update-profile/:id" element={<UpdateProfile />} />
<Route path="/settings" element={<Settings />} />
<Route path="/privacypolicy" element={<PrivacyPolicy />} />
<Route path="/licensing" element={<Licensing />} />
<Route path="/termsandconditions" element={<TermsandConditions />} />
</Route>

{/* 404 Page */}
<Route path="*" element={<Custom404 />} />
</Routes>
<Toaster />
</main>
{/* 404 Page */}
<Route path="*" element={<Custom404 />} />
</Routes>
<Toaster />
</main>
</ErrorBoundary>
);
};

Expand Down
37 changes: 23 additions & 14 deletions src/_root/pages/Profile.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import React from 'react';
import GridPostList from "@/components/shared/GridPostList";
import Loader from "@/components/shared/Loader";
import { Button } from "@/components/ui/button";
import { useUserContext } from "@/context/AuthContext";
import { useGetUserById } from "@/lib/react-query/queriesAndMutations";
import { useEffect } from 'react';
import {
Route,
Routes,
Expand Down Expand Up @@ -32,20 +34,23 @@ const Profile = () => {
const { user } = useUserContext();
const { pathname } = useLocation();

const { data: currentUser } = useGetUserById(id || "");
const { data: currentUser, isLoading, isError } = useGetUserById(id || "");

if (!currentUser)
return (
<div className="w-full h-full flex-center">
<Loader />
</div>
);
useEffect(() => {
// Refetch user data when the id changes
if (id) {
// You might need to implement a refetch function in your useGetUserById hook
// refetch();
}
}, [id]);

if (isLoading) return <Loader />;
if (isError || !currentUser) return <div>Error loading user profile</div>;

const copyToClipboard = async () => {
return await window.navigator.clipboard.writeText(window.location.href);
}


return (
<div className="profile-container">
<div className="profile-inner_container">
Expand Down Expand Up @@ -74,12 +79,16 @@ const Profile = () => {
</div>

<p className="max-w-screen-sm text-center small-medium md:base-medium xl:text-left mt-7">
{currentUser.bio.split('\n').map((line: String, index: Number) => (
<>
{line}
{index !== currentUser.bio.split('\n').length - 1 && <br />} {/* Add <br> except for the last line */}
</>
))}
{currentUser.bio ? (
currentUser.bio.split('\n').map((line: string, index: number) => (
<React.Fragment key={index}>
{line}
{index !== currentUser.bio.split('\n').length - 1 && <br />}
</React.Fragment>
))
) : (
"No bio available"
)}
</p>
</div>

Expand Down
37 changes: 37 additions & 0 deletions src/components/shared/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React, { ReactNode, useState, useCallback } from 'react';
import { ErrorBoundary as ReactErrorBoundary } from 'react-error-boundary';

interface ErrorBoundaryProps {
children: ReactNode;
}

function ErrorFallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}

export function ErrorBoundary({ children }: ErrorBoundaryProps) {
const [errorInfo, setErrorInfo] = useState<React.ErrorInfo | null>(null);

const handleError = useCallback((error: Error, info: React.ErrorInfo) => {
console.error("Uncaught error:", error, info);
setErrorInfo(info);
}, []);

return (
<ReactErrorBoundary
FallbackComponent={ErrorFallback}
onError={handleError}
onReset={() => setErrorInfo(null)}
>
{children}
</ReactErrorBoundary>
);
}

export default ErrorBoundary;
41 changes: 34 additions & 7 deletions src/components/shared/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,40 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import LogOut from "./Logout";
import { useSignOutAccount } from "@/lib/react-query/queriesAndMutations";
import { useToast } from "@/components/ui/use-toast";

export default function Settings() {
const navigate = useNavigate();
const { mutate: signOut, isSuccess } = useSignOutAccount();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const { mutateAsync: signOut, isSuccess } = useSignOutAccount();

useEffect(() => {
if (isSuccess) navigate(0);
if (isSuccess) {
navigate("/sign-in");
}
}, [isSuccess, navigate]);

const handleSignOut = async () => {
setIsLoading(true);
try {
await signOut();
toast({
title: "Logged out successfully",
});
} catch (error) {
console.error("Error signing out:", error);
toast({
title: "Error logging out",
description: "Please try again",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};

return (
<div className="saved-container">
<div className="flex w-full max-w-5xl gap-2">
Expand All @@ -30,8 +54,13 @@ export default function Settings() {
You can log out of your account at any time. This will sign you out of
all devices and sessions.
</p>
<button className="flex items-center gap-2 mt-4">
<LogOut fnc={signOut} />
<button
className="flex items-center gap-2 mt-4"
onClick={handleSignOut}
disabled={isLoading}
>
<LogOut fnc={handleSignOut} />
{isLoading && <span>Logging out...</span>}
</button>
</div>

Expand All @@ -46,8 +75,6 @@ export default function Settings() {
<div className="p-6 rounded-lg w-full shadow bg-[#09090A]">
<a className="text-2xl font-bold" href="/termsandconditions">Terms and Conditions</a>
</div>


</div>
);
}
22 changes: 9 additions & 13 deletions src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ const INITIAL_STATE = {
user: INITIAL_USER,
isLoading: false,
isAuthenticated: false,
setUser: () => {},
setIsAuthenticated: () => {},
setUser: () => { },
setIsAuthenticated: () => { },
checkAuthUser: async () => false as boolean,
};

Expand All @@ -36,8 +36,8 @@ const AuthContext = createContext<IContextType>(INITIAL_STATE);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate();
const [user, setUser] = useState<IUser>(INITIAL_USER);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isAuthenticated, setIsAuthenticated] = useState(false);

const checkAuthUser = async () => {
setIsLoading(true);
Expand All @@ -53,10 +53,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
bio: currentAccount.bio,
});
setIsAuthenticated(true);

localStorage.setItem("user", JSON.stringify(currentAccount));
return true;
}

return false;
} catch (error) {
console.error(error);
Expand All @@ -67,15 +66,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
};

useEffect(() => {
const cookieFallback = localStorage.getItem("cookieFallback");
if (
cookieFallback === "[]" ||
cookieFallback === null ||
cookieFallback === undefined
) {
navigate("/sign-in");
const storedUser = localStorage.getItem("user");
if (storedUser) {
const parsedUser = JSON.parse(storedUser);
setUser(parsedUser);
setIsAuthenticated(true);
}

checkAuthUser();
}, []);

Expand Down
8 changes: 4 additions & 4 deletions src/lib/appwrite/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,20 @@ export async function getCurrentUser() {
try {
const currentAccount = await getAccount();

if (!currentAccount) throw Error;
if (!currentAccount) throw new Error("No current account found");

const currentUser = await databases.listDocuments(
appwriteConfig.databaseId,
appwriteConfig.userCollectionId,
[Query.equal("accountId", currentAccount.$id)]
);

if (!currentUser) throw Error;
if (!currentUser.documents.length) throw new Error("No user found");

return currentUser.documents[0];
} catch (error) {
console.log(error);
return null;
console.error("Error getting current user:", error);
throw error; // Re-throw the error so it can be handled by the caller
}
}

Expand Down
Loading

0 comments on commit 29db49d

Please sign in to comment.