i have a loader that redircts to an /authroize page whenever the user opens my page, this is the code for my loader:
export function redirectLoader() {
const data = localStorage.getItem("persist:root");
const setStage = JSON.parse(JSON.parse(data).setStage);
const auth = JSON.parse(JSON.parse(data).isAuth);
if (!auth.user && !auth.admin) {
return redirect("/authorize");
} else if (setStage) {
return redirect(setStage);
}
return null;
}
after a user is authrized, the authorization is then saved in my localStorage with redux and redux-preisit, so that whenever the user come back the site, the session is saved
now this works fine, but for the first time it doesn't, it cause an error saying that can't read property of null of setStage
, when i refresh the error goes away.
i tried to use the promise based localStorage with redux-persist, the error still there in first run, i think the problem is that when i first open the site there is no localStorage initiated, so i should use useEffect instead of that loader maybe?
i fixed it using a check before i set my data and having a defualt varibale:
export function redirectLoader() {
const data = localStorage.getItem("persist:root");
const parsedData = JSON.parse(data);
let auth = {
user: "",
admin: "",
};
let setStage;
if (parsedData) {
auth = JSON.parse(parsedData.isAuth);
setStage = JSON.parse(parsedData.setStage);
}
if (!auth.user && !auth.admin) {
return redirect("/authorize");
} else if (setStage) {
return redirect(setStage);
}
return null;
}