Home > Back-end >  How to stay on the protected route, after refreshing page. React router 5.2.0
How to stay on the protected route, after refreshing page. React router 5.2.0

Time:12-06

I have public and protected routes, which implemented in the following logic

   useEffect(() => {
      checkIfAuthenticated(); //This function checks if the token is in localStorage
     // Initial state isAuthenticated = false
    }, []);
   const newHistory = useHistory()

   <Router history={newHistory}>
    {isAuthenticated ? (
      <Layout>
        <Switch>
          <Route
             exact
             path="/clients"
             component={Clients}
            />
          <Route
             exact
             path="/staff"
             component={Staff}
            />
          <Redirect to="/clients" />
        </Switch>
      </Layout>
       ) : (
      <>
       <Route path="/login" component={Login} />
       <Redirect to="/login" />
      </>)}
    </Router>

//store
checkIfAuthenticated() {
    const accessToken = localStorage.getItem("access_token");
    const refreshToken = localStorage.getItem("refresh_token");
    if (accessToken && refreshToken) {
      this.isAuthenticated = true;
    }
  }

The problem is when I refresh the page on the route /staff?page=1, the app initializes from scratch and I am redirected to the /clients route. Is there any way to handle this case? I.e when I refresh the private route, I should stay on the same page. Maybe I should save the current route to the localStorage?

CodePudding user response:

You must use redux-persist library to keep the value of isAuthenticated variable in localStorage after refresh.

Something like this:

import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import userReducer from './userReducer';

const persistConfig = {
  key: 'user',
  storage,
  whitelist: ['access_token', 'refresh_token'],
};

const persistedReducer = persistReducer(persistConfig, userReducer);

CodePudding user response:

If you are sure about persistance of variables in localStorage check this as well:

const accessToken = localStorage.getItem("access_token");
const refreshToken = localStorage.getItem("refresh_token"); 
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
  if (accessToken && refreshToken) {
    setIsAuthenticated(true);
  }
}, [accessToken , refreshToken ]);

const newHistory = useHistory()

<Router history={newHistory}>
{isAuthenticated ? (
  <Layout>
    <Switch>
      <Route
         exact
         path="/clients"
         component={Clients}
        />
      <Route
         exact
         path="/staff"
         component={Staff}
        />
      <Redirect to="/clients" />
    </Switch>
  </Layout>
   ) : (
  <>
   <Route path="/login" component={Login} />
   <Redirect to="/login" />
  </>)}
</Router>
  • Related