I need to navigate back to the original requested URL after login.
For example, the user enters www.eCart.com/Cart as the user is not authenticated, it will navigate to the login page www.eCart.com/login.
Once authenticated, it should navigate back to www.eCart.com/Cart automatically
my protectedRoute.js looks like this
import React from 'react'
import { connect } from 'react-redux'
import { Navigate, Outlet, useLocation, useNavigate} from 'react-router-dom'
export const withRouter = (Component) => { //works only for react16-17 //hooks
const Wrapper = (props) => {
const location = useLocation()
const navigate = useNavigate();
return (
<Component
navigate = {navigate}
{...props}
location={location}
{...props}
/>
);
};
return Wrapper;
};
const ProtectedRoute = ({component:Component, auth,...rest}) => (
auth.isAuthenticated ? <Outlet /> : <Navigate to={`/login/${rest.location.search}`} replace />
)
const mapStateToProps = (state) => ({
auth: state.auth
})
export default connect(mapStateToProps)(withRouter(ProtectedRoute))
my app.js is like this
function App(props) {
useEffect(() => {
store.dispatch(setCurrentUser())
}, [])
const grabProductsFromStorage = () =>{
const userId = decodeUser().user.id
const cartProducts = JSON.parse(localStorage.getItem("products"))
const context = {products: cartProducts, userId}
store.dispatch(addToCart(context))
localStorage.removeItem("products")
}
if(localStorage.getItem("token") && localStorage.getItem("products")){
grabProductsFromStorage()
}
return (
<Provider store={store}>
<Router>
<Routes>
<Route exact path="/" element={<Landing/>} />
<Route exact path="/products/:id" element={<ProductDetails/>} />
<Route exact path="/" element={<ProtectedRoute/>}>
<Route exact
path="/dashboard/*"
element={<Dashboard {...props} nestedRoute={Home} />}
/>
<Route exact path="/cart" element={<Cart />} />
</Route>
<Route exact path="/register" element={<Register/>} />
<Route exact path="/login" element={<Login/>} />
</Routes>
</Router>
</Provider>
);
}
Also, I've seen somewhere to use state in Navigate with the location it but when I'm doing it it's throwing an error of Unexpected use of 'location'