React + Express: Navbar not updating after login/logout without refresh

I'm building a web app with React (frontend on Netlify) and Express.js (backend on Vercel). Sessions are stored in PostgreSQL using express-session and connect-pg-simple.
I check authentication status in App.js using useEffect with Axios (withCredentials: true) and store it in a state authenticated, which I pass to the NavBar.
Problem: After login, the NavBar still shows the old links until I manually refresh the page.
App.jss:
const [authenticated, setAuth] = useState(false);
useEffect(() => {
const checkAuth = async () => {
const res = await axiosInstance.get('/auth/auth-status', { withCredentials: true });
setAuth(res.data.success);
};
checkAuth();
}, []);
Navbar.jsx:
function NavBar(props) {
return (
<nav>
{props.authenticated ? (
<>
<Link to="/new_review">Add a Review</Link>
<button onClick={logout}>Logout</button>
</>
) : (
<>
<Link to="/login">Login</Link>
<Link to="/sign-up">Sign Up</Link>
</>
)}
</nav>
);
}
``` thank you so much for answering...
Answer
Since the useEffect
in App.js
has empty dependancy so it will update the state once the page mounts first time (after refresh), you need to manually call the checkAuth
to update the state for status or you can use authContext
for saving auth related states and updating throughout your app
In login function add the checkAuth
function to update the state manually after button is clicked
function Login({ checkAuth }) {
const handleLogin = async () => {
const res = await axiosInstance.post('/auth/login', loginData, { withCredentials: true });
if (res.data.success) {
await checkAuth();
navigate('/');
}
};
return <button onClick={handleLogin}>Login</button>;
}
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles