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 };
};