When I log in to my react app, it automatically redirects me to the login page because of this private route.
<Route exact path="/">{!user ? <Redirect to="/auth" /> : <Dashboard />}</Route>
But instead of redirecting me to the login page, it should redirect me to the Dashboard page.
What my react app does:
- When I log in to my react app, it should redirect me to the logged-in user subdomain using this piece of code.
window.location.href = `http://${data?.result?.username}.localhost:3000?token=${data?.token}`;
- I am also passing a
token
as a parameter so that I can decode this token and save the user data to the local storage when the user gets redirected to the subdomain.
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get("token");
if (token) {
const decodedData = jwt_decode(token);
dispatch({ type: "AUTH", data: { result: decodedData, token } });
}
user && dispatch(getInvoices());
}, [dispatch, user]);
Complete Code:
import React from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, Suspense } from "react";
import { getInvoices } from "./actions/invoices";
import Sidebar from "./components/layouts/Sidebar";
import jwt_decode from "jwt-decode";
// custom components
const Dashboard = React.lazy(() => import("./components/dashboard/Dashboard"));
const Auth = React.lazy(() => import("./components/authForm/Auth"));
function App() {
const dispatch = useDispatch();
const user = useSelector((state) => state.auth.authData);
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get("token");
if (token) {
const decodedData = jwt_decode(token);
dispatch({ type: "AUTH", data: { result: decodedData, token } });
}
user && dispatch(getInvoices());
}, [dispatch, user]);
return (
<Router>
<div>
<Sidebar />
<Switch>
<Suspense fallback={<div>Loading..</div>}>
<Route exact path="/">
{!user ? <Redirect to="/auth" /> : <Dashboard />}
</Route>
<Route path="/auth">{!user ? <Auth /> : <Redirect to="/" />}</Route>
</Suspense>
</Switch>
</div>
</Router>
);
}
export default App;