0

I have a login functionality in my reactjs app, when user login my app im storing its refresh and access token in my redux store my initial store of user is data:{ isLoggedIn:false, userData:null } after login i am saving userData and setting isLoggedin:true ,and also i am storing accesstoken in my browser cookie also Now i have to manage the userData with respect to cookie ,cookie expiration time is one hour so I have to create a middleware for every api call to validate cookie from my browser and if its expired then create a new cookie and store it to browser cookie , i have api/refreshToken api to create new token.. my refresh token expiry is 24hour so i also want to check is refresh token is expired then user will automatically logout if cookie is null

Every time i am any api after some time of login i am getting unauthorized error so i want to update my cookie before any api call. And also want to restrict routes if user is not logged, and i have to manage my redux store according to cookie and refresh token validations..

  const userInfo = useSelector((state) => state.userReducer);

  const isUserLoggedIn = userInfo.userData.isLoggedIn;



  <Route
          path="/"
          element={isUserLoggedIn ? <DashBoardLayout /> : <LoginPage />}
        >
          {isUserLoggedIn ? (
            <Route index element={<Overview />} />
          ) : (
            <Route index element={<LoginPage />} />
          )}

i have used persist redux to store in local storage ,

1 Answer 1

2

Create A high order function for restricting the routes.

import React from "react";
import secureLocalStorage from "react-secure-storage";
import { Navigate, Outlet } from "react-router-dom";

const PrivateComponent = () => {
  const auth = JSON.parse(secureLocalStorage.getItem("adminInfo"));
  console.log("auth", auth);
  return auth ? <Outlet /> : <Navigate to="/" />;
};

export default PrivateComponent;

same like this and wrap this component on the routes.

Sign up to request clarification or add additional context in comments.

1 Comment

You dont need to wrap react secure storage with JSON.parse, the library is capable of remembering the object types

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.