So I need to prevent the user from going back to the profile page (/profile) after he already selected a profile. I'm storing the profile selected inside the application state.
Scenario wanted: User goes to /profile, select a profile, then goes to '/' (which is my home), and can navigate to /exams if he wants. BUT, he can't go back to /profile, since he's already inside the application with a profile stored in the state. If he tries to go to /profile, through browser back-arrow or even typing /profile in the url, the current page simply reloads.
What's the best way to achieve this?
OBS: this const { id } = useSelector... is the const that retrieves the profile from the state, so I have to use this as condition, but I don't know how.
Therefore, if the user have an id that's not empty (which means he already selected a profile), he can't go back to profile. Other than that, he can visit /profile.
Below follows my route.tsx:
const Exams = lazy(() => import('../pages/private/Exams'));
const Home = lazy(() => import('../pages/private/Home'));
const ProfileSelector = lazy(() => import('../pages/private/ProfileSelector'));
const { id } = useSelector((state: RootState) => state.profile);
const AppRoutes = () => {
return (
<Router history={history}>
<Suspense fallback={<LoadingPage />}>
<Switch>
<Route exact path={'/'} component={Home} />
<Route exact path={'/exams'} component={Exams} />
<Route exact path={'/profile'} component={ProfileSelector} />
</Switch>
</Suspense>
</Router>
);
};
export default AppRoutes;
My profile store if there's any use:
interface UserProfileModel {
id: string;
council: string;
state: string;
number: string;
description: string;
}
const initialState: UserProfileModel = {
id: '',
council: '',
state: '',
number: '',
description: '',
};
export const userProfileSlice = createSlice({
name: 'profile',
initialState,
reducers: {
selectProfile: (state, action: PayloadAction<UserProfileModel>) => {
return {
...state,
...action.payload,
};
},
clearProfile: () => initialState,
},
});
export const { selectProfile, clearProfile } = userProfileSlice.actions;
export default userProfileSlice.reducer;
Set a state for example profileSelected to true when the user selects a profile then:
put
{profileSelected ? null : <Route exact path={'/profile'} component={ProfileSelector} />}
instead of
<Route exact path={'/profile'} component={ProfileSelector} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.