Skip to content

Refactor redirect-on-login behaviour using location state

Axel Bocciarelli requested to merge refact-redirect into master

Opening as draft, as !469 (merged) needs to be merged first, but this is reviewable.

As mentioned in !469 (merged), I'm now refactoring the behaviour that takes the user back to the location they initially requested after logging in. Contrary to what I said, though, I decided to use the location state to store the redirection info rather than the URL, as this simplifies storing the full location (search params, etc.) without cluttering the URL with the root domain.

Previously, this behaviour was implemented with Redux:

  1. Logged-out user tries to visit a private location other than /, like /scanviewer.
  2. PrivateRoute saves the current location in the store and redirects to /login.
  3. After a successful log-in, Redux redirects /, which renders PrivateRoute again.
  4. PrivateRoute sees that the user is logged in and that there is a redirect location object in the store, and so decides to redirect to that location.

Now, I'm using location state (the arbitrary data you can store when using the History API) to simplify the whole process:

  1. Logged-out user tries to visit any private location like /scanviewer, including /.
  2. PrivateRoute redirects to /login and saves the current location in location state.
  3. LoginRoute renders, user logs in, LoginRoute re-renders (because auth state changes in Redux store)
  4. LoginRoute detects that the user is now logged in and redirects to the location object stored in location state (or to / if the user landed on the login page directly)
  5. PrivateRoute sees that the user is logged in and renders the app (no redirection needed here).

I wrote more steps, but they are less convoluted. All the redirects are done declaratively in React components; there's one fewer global state value; the redirect is done by LoginRoute instead of PrivateRoute, which means we avoid a double redirect (previously to / and then to the redirect location).

Finally, one added benefit is that when the user logs out and logs back in right away, they go back to where they were. Previously they would end up back to /.

Edited by Axel Bocciarelli

Merge request reports

Loading