In a React project, when logged in and entered to landing page works fine but, on reloading redirects to login page keeping url unchanged. Please refer code below
This is the routing structure
<Routes>
<Route path={home} element={<Navigate to={companyPage} />} />
<Route
path={companyPage}
element={
<ProtectedRoute>
<CompanyPage />
</ProtectedRoute>
}
/>
<Route path="*" element={<RouteNotFound />} />
</Routes>
ProtectedRoute.js (Here the routes are protected)
function ProtectedRoute({ children }) {
const { authorized } = useContext(AutorizationContext);
return authorized === true ? children : <Navigate to={RouteConstant.sign} />;
}
ProtectedRoute.propTypes = {
children: PropTypes.element.isRequired
};
Routes.js (Here each of routes are defined)
get sign() {
return "/signin";
},
get home() {
return "/home";
},
get company() {
return `${this.home}/company`;
},
get companyPage() {
return `${this.company}/companypage`;
}
What could be the best optimal solution? Any suggestions highly appreciated Please refer to the codesandbox: https://codesandbox.io/s/withered-frog-hp0bu7 Enter name and password both as 'test'
CodePudding user response:
your state variable authorized
is switching from true to false on page refresh
one solution would be using localStorage
to store authorized
value in a temporary variable
the useLocalStorage
hook :
// file path : /src/use-local-storage.js
import { useState } from "react";
function UseLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
export default UseLocalStorage;
and in your App.js
try this :
import React, { useEffect, useState } from "react";
import { BrowserRouter } from "react-router-dom";
import AutorizationContext from "./context/auth-context";
import Login from "./pages/login/Login";
import HomePage from "./pages/home/HomePage";
import UseLocalStorage from "./use-local-storage";
export default function App() {
const [authorized, setAuthorized] = useState(false);
const value = { authorized, setAuthorized };
const [savedAuth, setSavedAuth] = UseLocalStorage();
useEffect(() => {
setAuthorized(savedAuth);
}, []);
useEffect(() => {
setSavedAuth(authorized);
}, [authorized, setSavedAuth]);
return (
<BrowserRouter>
<AutorizationContext.Provider value={value}>
{!authorized ? <Login /> : <HomePage />}
</AutorizationContext.Provider>
</BrowserRouter>
);
}
full sandbox here