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.
2
Answers
I had an import wrong
the correct:
Although you already found your problem, you should review the status update you do, the correct thing would be to update the value of your isAuthenthicated key, or else it makes no sense to give it a default value of that type. See how you should update with useState.