Refactor redirect-on-login behaviour using location state
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:
- Logged-out user tries to visit a private location other than
/
, like/scanviewer
. -
PrivateRoute
saves the current location in the store and redirects to/login
. - After a successful log-in, Redux redirects
/
, which rendersPrivateRoute
again. -
PrivateRoute
sees that the user is logged in and that there is aredirect
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:
- Logged-out user tries to visit any private location like
/scanviewer
, including/
. -
PrivateRoute
redirects to/login
and saves the current location in location state. -
LoginRoute
renders, user logs in,LoginRoute
re-renders (becauseauth
state changes in Redux store) -
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) -
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 /
.