I want to direct user to the login page if he/she is not authorized. I wrote the bottom code for this purpose. Root route is login page, and AdminPanel page is for admin. If data.success is true this means person is admin. But this code render 404 not found on http://localhost:3000/user url. How can I fix this issue?
const App = () => {
const [auth, setAuth] = useState(false);
const authControl = async () => {
try {
const res = await axios({
url: "https://localhost:44357/api/Auth/user",
withCredentials: true,
});
console.log(res.data.success);
if (res.data.success) setAuth(true);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
authControl();
}, []);
return (
<div>
<BrowserRouter>
<Route path="/" exact component={Login} />
<Route
path="/user"
render={() => {
auth ? <AdminPanel /> : <Redirect to="/" />;
}}
/>
<Route render={() => <h1>404 Not Found</h1>} />
</BrowserRouter>
</div>
);
};
you need to wrap the <Route />s in a <Switch /> from react router.
something like this:
<Switch>
<Route path="/public">
<PublicPage />
</Route>
<Route path="/login">
<LoginPage />
</Route>
</Switch>