I am following a course to learn how to implement a login system. While creating the AuthProvider to test the context functionality, I changed the default value of isAuthenticated in the useState to “true”. However, when using it in the ProtectedRoute, it returns the value set in the createContext and does not allow me to access the protected routes. If I change the value in the createContext to “true”, it works, as if it is ignoring the useState.
P.S.: The log “AuthProvider isAuthenticated:” is not being printed, but the others are.
AuthProvider.js
const AuthContext = createContext({
isAuthenticated:false,
});
function AuthProvider({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState(true); // Ajusta el valor inicial según tus necesidades
console.log('AuthProvider isAuthenticated:', isAuthenticated);
return (
<AuthContext.Provider value={{ isAuthenticated }}>
{children}
</AuthContext.Provider>
);
}
const useAuth = () => useContext(AuthContext);
export{ AuthProvider, useAuth}
ProtectedRoute.js
function ProtectedRoute() {
const auth = useAuth();
console.log('isAuthenticated:', auth.isAuthenticated); // Agrega este console.log para verificar el valor
return auth.isAuthenticated ? <Outlet /> : <Navigate to="/" />;
}
export { ProtectedRoute };
App.js
function App() {
return (
<>
<BrowserRouter>
<AuthProvider>
{console.log('AuthProvider wrapping components')}
<BookProvider>
<HeaderNav/>
<Routes>
<Route path="/:username" element={<ProfilePage />}/>
<Route path="/:username/books" element={<BookTablePage/>}/>
<Route element={<ProtectedRoute />}>
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="/" element={<p>HOLA MUNDO</p>}/>
<Route path="*" element={<p>Not found</p>} />
</Routes>
</BookProvider>
</AuthProvider>
</BrowserRouter>
</>
);
}
export default App;
I want the useState to modify the default value of the createContext.
Tavio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.