How to persist on a route using React router with Reactjs?

Asked

Viewed 40 times

0

I have a site in React, and would like to know how to persist on a route. For example: When I’m on the profile page and refresh the page, it redirects me to Dashboard. Does anyone have any idea how I do for when I give Load I can stay in the profiling route?

File Router.js

import PropTypes from 'prop-types';
import { Redirect, Route } from 'react-router-dom';

import { useAuth } from '../contexts/auth';

const RouteWrapper = ({ component, isPrivate, isNotFound, ...props }) => {
  const { signed } = useAuth();

  if (isNotFound) 
    return <Route { ...props } component={ component } />;
  
  if (!signed && isPrivate) 
    return <Redirect to="/" />;

    
  if (signed && !isPrivate) 
    return <Redirect to="dashboard" />;
  
  return <Route { ...props } component={ component } />;
};

RouteWrapper.propTypes = {
  component: PropTypes.oneOfType([
    PropTypes.element,
    PropTypes.func
  ])
};

export default RouteWrapper;

Index.js file of routes

import { BrowserRouter, Switch } from "react-router-dom";
import Route from './Route';

import SignIn from "../pages/SignIn";
import Dashboard from "../pages/Dashboard";
import Profiles from "../pages/Profiles";
import NotFound from "../pages/NotFound";

export default function Routes() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={SignIn} isLogin />
        <Route exact path="/dashboard" component={Dashboard} isPrivate />
        <Route exact path="/perfils" component={Profiles} isPrivate />

        <Route component={NotFound} isNotFound />
      </Switch>
    </BrowserRouter>
  );
}

2 answers

1

That function RouteWrapper possibly giving conflict. You yourself put in it that case the user !signed && isPrivate it is redirected to the root folder. Try to comment on that part and make a <Switch> simple in the route file to see if it works!

0

I was able to resolve it by creating separate route files. Authroutes and Defaultroutes, then valid the Signed, and if it is true I Reverse the Authroutes otherwise Reverse the Defaultroutes, so I have specific routes for both cases :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.