I am making an app that has a premium version and a free version. When a user logs in, the data for that user is fetched using an API. I have a component that checks whether the user is a pro user or a free user, depending on that information, the app is rendered.
Now, whenever a user signs in, it takes a couple of seconds for the user data to be set in the context API, but the Auth component decides to render the free version before the data is set.
How I am retaining the user on login and refresh:
useEffect(() => {
async function retainSession() {
try {
await Auth.currentSession();
let email = await Auth.currentAuthenticatedUser();
email = email.attributes.email;
setAuth(true);
Axios.get(`API_URL/user/getUser/${email}`).then(
(res) => {
setUser(res.data[0]);
}
);
localStorage.setItem("membership", user.membership);
} catch (error) {
console.log(error);
}
}
retainSession();
});
And my Auth function that protects the routes:
const RequireAuth = ({ allowedRoles }) => {
const location = useLocation();
const { auth } = useAuth();
const { user } = useUser();
return auth &&
(user?.membership === "pro" ||
localStorage.getItem("membership") === "pro") ? (
<Outlet />
) : auth ? (
<Navigate to="/unauthorized" state={{ from: location }} replace />
) : (
<Navigate to="/" state={{ from: location }} replace />
);
};
Now on login and refresh, initially the data is loaded but when I refresh on a protected route, it redirects me to the homepage. But I can access the protected routes once the data is loaded.
How do I fix this issue so that the user is completely retained and after login, refresh does not cause a redirect or hides the data.