I have a user authentication app, once a user logs in I save his data on the redux store and use it to manage the authenticated state through redux. But this never gave real-time data. Say, that the user got blocked in the middle of his session. There were no options to log him out unless he visited a protected route in the server. So I created a costume hook to make API calls to the server to validate the user. The problem is I created a protected route component and wrapped all the routes in this component. I expected to make the API call when he switched from component to component. But still, the Protected route is the parent and there were no state changes happening there. So the API call is not made every time he visits a component. One way I could do this is by invoking this hook in every component which the user visits. But that’s not an efficient approach. How can I make the API call whenever a child component is changed? Or this there any other method were I can acquire this functionality?
This is my Route structure
<Route element={<ProtectedRoutes />}>
<Route element={<DashboardHeader />}>
<Route path="dashboard" element={<Dashboard />}></Route>
<Route path="classroom/:classroom_id" element={<ClassroomLayout />}>
<Route
path="summary"
element={<ClassroomSummary />}
errorElement={<Error />} />
</Route>
</Route>
</Route>
//Protected Route were the hook useAuth call is made. Hook is working perfeclty fine!
const ProtectedRoutes: React.FC<DashboardProps> = () => {
const role = useRole();
const navigate = useNavigate()
const { loading, user, error } = useAuth(role);
if (loading) return null
if (error) navigate('/');
return user ? <Outlet /> : <Navigate to='/' />
}