I have a doubt regarding dynamically rendering the logged in user's name in the NavBar in react.
So my app is structured in the following way
<App>
<Header/>
<Router>
....
<Router/>
<Footer/>
<App/>
Now inside the header component, I need to display "Welcome <user>" whenever the user is logged in. Here are some solutions that I thought of,but Not sure if I'm missing out on anything.
-) I think it can be accomplished in Angular by BehaviorSubject, but in this scenario, I'm clueless.
Is there any solution or method that I am missing? Thanks in advance
You can send the user as a prop to the header. That is kind of the preferred method. Have the user login and save their app state with redux of the useState hook that is now available in React.
To your second question, JWTs preserve session data. Rerendering the page won't cause that to disappear. Well-designed apps have JWT with an expiration time (usually 20 minutes or less).
I worked on a voting application that did exactly what you're looking for and did not require any global state management. Feel free to pick through it. It's an open-source project. I think we used Auth0 or Google's Oauth library to do authentication.
Here's the code for the React header(navbar): https://github.com/poll-pal/poll-pal/blob/master/src/Components/Header/Header.js
Here's the code for the Express server that backed it: https://github.com/poll-pal/poll-pal/blob/master/server/routes/auth.js
At first if you want to keep your user logged in then you have to store the JWT somewhere. Here by 'somewhere' I mean, so that you can access it on next reload.
In my maximum project I store my JWT in local-storage. It works something like this
JWT in local-storage also in my reducer.initial_state = {
userName: localstorage.getItem('user_name')
}
That's how you can keep your user logged in and at the time of logout erase the local-storage as well as the reducer.