Skip to content

Commit

Permalink
Custom auth hook to retrieve current session data (#98)
Browse files Browse the repository at this point in the history
* Remove unnecessary import

* Fix bug in validating Spotify auth

* Implement and use custom auth hook
  • Loading branch information
Advayp authored Jan 31, 2025
1 parent 5bc3929 commit 9ef60ea
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 18 deletions.
22 changes: 9 additions & 13 deletions frontend/app/main/index.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import { getCurrentSession } from '@/services/auth/me';
import { User } from '@/types';
import { useEffect, useState } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { SafeAreaView, Text } from 'react-native';

const Index = () => {
const [user, setUser] = useState<User>();

useEffect(() => {
const call = async () => {
const [currentUser, error] = await getCurrentSession();
setUser(currentUser!);
};
call();
}, []);
const { user, error, isLoading } = useAuth();

return (
<SafeAreaView>
<Text>{user?.username}</Text>
{isLoading ? (
<Text>Loading</Text>
) : error ? (
<Text>{error}</Text>
) : (
<Text>{user?.username}</Text>
)}
</SafeAreaView>
);
};
Expand Down
5 changes: 1 addition & 4 deletions frontend/app/register/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import { register } from '@/services/auth/register';
import { Button } from '@/components/Button';
import { Spinner } from '@/components/Spinner';
import { useRouter } from 'expo-router';
import {
getSpotifyCredentials,
validateSpotifyCredentials,
} from '@/utils/spotify';
import { validateSpotifyCredentials } from '@/utils/spotify';

const Index = () => {
const [username, setUsername] = useState('');
Expand Down
30 changes: 30 additions & 0 deletions frontend/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { getCurrentSession } from '@/services/auth/me';
import { User } from '@/types';
import { useEffect, useState } from 'react';

export const useAuth = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string>();
const [user, setUser] = useState<User>();

const fetchData = async () => {
setIsLoading(true);
setError(undefined);
const [user, error] = await getCurrentSession();

if (error) {
setError(error.error);
setUser(undefined);
} else {
setUser(user!);
}

setIsLoading(false);
};

useEffect(() => {
fetchData();
}, []);

return { user, error, isLoading };
};
2 changes: 1 addition & 1 deletion frontend/utils/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,5 @@ export const validateSpotifyCredentials = async () => {
return false;
}

return accessToken && refreshToken;
return !!accessToken && !!refreshToken;
};

0 comments on commit 9ef60ea

Please sign in to comment.