Setting User status to a state variable
Setting user status to a state variable is a crucial way to ensure that conditional and declarative rendering works for authenticated users. Making the ability to view components dependent on being logged in is necessary for security and data management.
In this app, users are logging in to a site that organizes outdoor gear to a library and allows you to attach it to planned trips. for models, there are “items” (gear), “trips”, and then a join table, “packlists”, that create a many-to-many relationship between items and trips. All 3 of these models belong to a user though, to ensure that a user is only seeing their information.
Firstly, in order to access user status on the front end, we set up a state variable that has a default value of null (which is equivalent to “logged out”).
Within the App component where this user state lives, there is also a useEffect hook that, on page load, makes a fetch request to the backend to determine if there is a logged in user
This code seeks out whether there is an active user session and if so, sets the value of the user state variable to the user object. Once that state variable is updated to the value of a user, the rest of the components can be conditionally rendered based on the user that is set to the state variable.
Logging in has a similar set of code that sends a post request to sessions#create for creating the session and user object that can then be assigned to the user state variable.
Logging out correspondingly sends a fetch request to sessions#destroy and resets the user state variable back to null.
With these routes and fetch requests set up, we can use conditional rendering to give users access to their attached data. Because all of the data attaches to a user in addition to the other relationships, all other fetch requests can be made within a particular user’s set of data.
An example of some of the conditional rendering that the user state variable unlocks for us is the display of particular pages. Given, for example, this:
We can see here that a ternary within the switch router allows the page to render either the login components, if there is no user logged in, or the user’s homepage component if they are logged in. This ensures that any logged out user will only see the log-in page until they have successfully logged in. This is foundational functionality to how we experience and build apps that support a strong user experience.