PHP Classes

File: frontend/src/app/hooks/useAuth.ts

Recommend this page to a friend!
  Classes of Edward Paul   Task List   frontend/src/app/hooks/useAuth.ts   Download  
File: frontend/src/app/hooks/useAuth.ts
Role: Auxiliary data
Content type: text/plain
Description: Auxiliary data
Class: Task List
Manage and share a list of tasks
Author: By
Last change:
Date: 22 days ago
Size: 1,073 bytes
 

Contents

Class file image Download
'use client'; import { useEffect, useState } from 'react'; import { useRouter } from 'next/navigation'; import { profile } from '@/services/auth'; export const useAuth = (redirectAuthenticated = false) => { const router = useRouter(); const [authenticated, setAuthenticated] = useState<boolean | null>(null); useEffect(() => { const checkAuthentication = async () => { try { const token = localStorage.getItem('token'); if (!token) { throw new Error('No token found'); } const response = await profile(); setAuthenticated(true); if (redirectAuthenticated) { router.push('/tasks'); } } catch { setAuthenticated(false); if (!redirectAuthenticated) { router.push('/login'); } } }; checkAuthentication(); }, [redirectAuthenticated, router]); return authenticated; };