I am trying to protect a couple of pages from logged out users. I’m fairly new to react so this is error is new to me, unsure what I am doing wrong…
This is my App.js
import React from 'react';
import {
BrowserRouter as Router,
Route,
Routes,
Navigate,
} from 'react-router-dom';
import CustomNavbar from './components/common/Navbar';
import HomePage from './pages/HomePage';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import CreateJobPage from './pages/CreateJobPage';
import JobsPage from './pages/JobsPage';
import JobPage from './pages/JobPage';
import DashboardPage from './pages/DashboardPage';
import useAuthentication from './utilities/useAuthentication';
function App() {
const { isLoggedIn } = useAuthentication();
return (
<Router>
<CustomNavbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/create-job" element={<CreateJobPage />} />
<Route path="/jobs" element={<JobsPage />} />
<Route
path="/job/:id"
element={isLoggedIn ? <JobPage /> : <Navigate to="/login" />}
/>
<Route
path="/dashboard"
element={isLoggedIn ? <DashboardPage /> : <Navigate to="/login" />}
/>
</Routes>
</Router>
);
}
export default App;
I tried to protect pages with doing authentication on page, but I feel like this way would be better? I am unsure, again – I am new :(.
This is my useAuthentication.js
// userAuthentication.js
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
const useAuthentication = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userData, setUserData] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const checkLoginStatus = async () => {
try {
const response = await fetch('http://localhost:5000/api/check-auth', {
method: 'GET',
credentials: 'include',
});
if (response.ok) {
const { message, userData } = await response.json();
setIsLoggedIn(true);
setUserData(userData);
} else {
navigate('/login');
}
} catch (error) {
console.error('Error checking authentication:', error);
navigate('/login');
}
};
checkLoginStatus();
}, [navigate]);
return { isLoggedIn, userData }; // Return isLoggedIn and userData
};
export default useAuthentication;
Trying to restrict access to pages where a user should be logged in. Doing it on-page wasn’t doing what I expected it to. For example, I make a call to my backend for job details on a certain job so it takes a couple of sections to fetch data – when I tried to check for logged in status, the job would still load in the backend, when done, it would then redirect to login…