The protected route is not working as expected, even though the user details are getting saved in local storage after login.
I have created a simple project using "react-router-dom": "^6.8.2" and Context APIs.
Code repo: https://github.com/ashusharmatech/farzi
I created a simple route in app.jsx:
createRoutesFromElements(
<Route>
<Route path="/" element={<Layout />}>
<Route index element={<h1>Home page</h1>} />
<Route element={<AuthRequired />}>
<Route path="protected" element={<h1>Super secret info here</h1>} />
</Route>
</Route>
<Route path="/login" element={<Login />} />
</Route>
)
Created few hooks for authentication:
Use Auth -> https://github.com/ashusharmatech/farzi/blob/main/src/hooks/useAuth.ts
Use Local Storage -> https://github.com/ashusharmatech/farzi/blob/main/src/hooks/useLocalStorage.ts
Use User -> https://github.com/ashusharmatech/farzi/blob/main/src/hooks/useUser.ts
Once the login is invoked user details are getting stored in the local storage but it return null while retrieval of the user values in AuthRequired components.
export default function AuthRequired() {
const { user } = useAuth();
useEffect(() => {
console.log("Use Effect is "+JSON.stringify(user));
})
return user? <Outlet /> : <Navigate to="/login" />;
}
I am assuming its due to the context is returning the default values always.
import { createContext } from 'react';
import { User } from '../hooks/useUser';
interface AuthContext {
user: User | null;
setUser: (user: User | null) => void;
}
export const AuthContext = createContext<AuthContext>({
user: null,
setUser: () => {},
});
Can you suggest what is missing in this code ?