1

I've coded the following useAuth hook in order to check if user is authorized to see certain components. I restrict them with a HOC. But event getting the user from the backend and entering the true condition in the if statement (where console.log states that the user is authenticated), isAuthenticated is received false. What am I missing here

PrivateRoutes.tsx

import React from 'react';
import { useAuth } from './Auth';

import { Outlet, Navigate } from 'react-router-dom'

const PrivateRoutes = () => {
    const { isAuthenticated } = useAuth();
    return(
        isAuthenticated ? <Outlet/> : <Navigate to="/login"/>
    )
}

export default PrivateRoutes

Auth.tsx

import { useState, useEffect } from 'react';
import axios from 'axios';

const instance = axios.create({
    baseURL: 'http://localhost:8000',
});

export const useAuth = () => {
    const [isAuthenticated, setIsAuthenticated] = useState(false);


    const getUser = async () => {
        const response = await instance.get('/user', { withCredentials: true });

        if (typeof response.data.user === 'object' && response.data.user !== null) {
            console.log("authenticated")
            setIsAuthenticated(true);
        } else {
            console.log("not authenticated")
            setIsAuthenticated(false);
        }
    };

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

    console.log(isAuthenticated)
    return { isAuthenticated };
};
Juan Bilardi
  • 11
  • 1
  • 3
  • The initial state is false, which will always cause a navigation to the login page. – Benjamin Jan 20 '23 at 21:56
  • The initial `isAuthenticated` state matches the unauthenticated state, so the redirection to log in occurs. The private route component should wait for the authentication check to complete prior to making a decision to redirect or render the protected content via the outlet. – Drew Reese Jan 20 '23 at 22:02

0 Answers0