Display logged in user's first name onto page (from database) - database

In preparing a welcome page after a user has logged in, I'd like the page title to display their first name which is found in the user ID database (e.g - "Welcome, Sally!"). This is a bit different than just using a cookie to relay the username in a location; like for example in the top corner to access user settings.
The site is being built with React, if that affects the code needed.
Any suggestions?

are you asking how to get the username in the app state? or just how you would render that?
if you already have the firstname in an auth object in state you could do something like this:
class WelcomePage extends Component {
render() {
const { auth } = this.props
var pageTitle = `Welcome, { auth.firstname }`
return (
<h1>{ pageTitle }</h1>
)
}
}
export default WelcomePage
otherwise I would need more information to understand what you're asking

Here is a solution I worked out that seems to do the job. This lies within the React component for the page rendering.
render: function(){
var user = JSON.parse(localStorage.getItem('user'));
...
return (
<div>
<h2>Welcome, {user.firstname1}!</h2>
</div>
Here's a quick screen shot of the result ("Candy" being the logged-in user's first name):

Related

Reactjs: Show logged in or log in accordingly to session

I am trying to get better in react and I would like to do it everything correctly which is why I am asking for your opinions and help.
I am building a project in NextJS and I have a layout component which contains components which are rendered multiple times such as header, footer etc.
I this header, I have a "Sign in" and "Sign out" button. I'd like it to only show one of them accordingly to your session status.
I use a sessionid which contains some more info in the database and this sessionid is stored in a httponly cookie.
It is stored in the database with data:
id
sessionid
userid
expires
Would you add or remove anything to this?
So my question is:
How would you check for a session and then render x accordingly? Would you just send an api call each request that checks the session or? Should I maybe use useContext and create a provider which can then send the session with the provider?
I'm quite lost on how to do it the best way so the flow is smooth as f*ck.
It depends how strict you want to be with it.
One option would be to simply check the existence of the cookie and adjust according to that. You can use js-cookie for that.
The better option, in my opinion, is to verify the cookie with your backend. You should set up an endpoint that simply verifies / parses the cookie and returns something like the user_id, or ismply a boolean indicating whether the user is logged in.
Given that you are using Next, you can add this call to your App's getInitialProps() like this:
App.getInitialProps = async () => {
let loggedIn;
try {
({ data: {loggedIn} } = await axios.get('/api/v1/auth/checkCookie'));
} catch (err) {
console.log('Error checkingCookie', err.message );
}
return {
loggedIn,
}
}
Your loggedIn variable will then be available in the props of your App, like:
function App({currentUser}) {
if (currentUser) {
return <div>Logged In</div>
} else {
return <div>Logged Out</div>
}
}

Google analytics UserId view is not working with react

I want to track users by their login ID in a ReactJS application. I followed all of the tutorials on the documentation to set up the User Id View. I enabled userId tracking in google analytics and I've set a userId upon logging in. this is my login function :
const accessToken = data.data.accessToken;
sessionStorage.setItem("accessToken", accessToken);
localStorage.setItem("userId", data.data.data.user._id);
console.log(typeof(data.data.data.user._id));
// set UserId with reactGa
ReactGa.set({ userId: data.data.data.user._id });
navigate("/gaLogin");
I've initialized react-ga in my layout component and it works fine with other normal views. but in the userId view it doesn't work and it shows nothing (0 active users...) Idk if it's related to React or I'm doing something wrong.
PS: sometimes it detect a user upon logging in and it stops tracking right after.
The following is working for me, as used in the top level parent component.
First
import ReactGA from "react-ga4";
Then
useEffect(() => {
if (isCookieConsent && initialised) {
ReactGA.initialize("ga4-someid-1", {
gaOptions: {
userId: user ? user.id : "n/a",
},
});
ReactGA.send("pageview");
}
}, [user, pathname, isCookieConsent, initialised]);
Then create a user-explorer view to see the analytics
https://support.google.com/analytics/answer/9283607#zippy=%2Cin-this-article

How to handle user permission base on role?

I'm creating an Admin Dashboard with React, and manage access base on user role (Admin, Client and User). Each role will have permission like:
Admin: can view Dashboard and CRUD posts
Client: can view Dashboard and create and read posts
User: can't view Dashboard and only read posts
Is there a way to implement this or npm package that supports with role n permission like this?
thanks!
this is demo code
https://codesandbox.io/s/hardcore-shape-6mvos?file=/src/App.tsx
In your case to handle react rendering your best chose is NextJs
By NextJs you can controller your rendering page before sending to your client
I deal with this every day. I have a component called Permission. It takes in the name of the permission(s) as a prop and checks to see if the user (stored in redux) has those permissions. If so, it returns the children of the Permission component.
Permission.js:
const Permission = ({ allowedPermissions, children }) => {
function isVisible() {
let visible = true;
allowedPermission.forEach((permission) => {
if (!user.permissions.includes(permission) {
visible = false;
}
});
return visible;
}
return isVisible() ? children : null;
}
Usage, which can include being wrapped around react-router switch/route statements:
<Permission allowedPermissions=["admin"]>
<Button onClick={() => deletePost()}>Delete</Button>
</Permission>

Why is my information passed lagging behind by one?

I am trying to code a simple React app that requires a user to sign in with Google before sample data can be accessed in the app. I would like a welcome message to display upon login that says "Welcome, [name]!" Currently, this function is working, but it's lagging behind by one sign-in.
The beginning state of my app
This is how the app appears at the beginning.
The app after one login
This is how the app appears after one login. Note that instead of getting the name from the user's Google account, it displays the default value of "default".
The app after two or more logins to the same account
After logging out and logging back in again, however, the app functions normally, showing the welcome message with the user's name. I've tried logging in with a different account, and the lag persists, i.e. "default" displays when logging in with Naomi, "Naomi" displays when logging in with Ally, "Ally" displays after logging out and logging back into Ally.
I've tried logging the variable with the user's name (userName) to the console right before information is passed, and it appears to be firing AFTER the log-in is completed, but I'm not sure why.
The code I hope is relevant is below.
import React from 'react';
import Login from './Login';
var userName = "default";
class LoginButton extends React.Component {
// some other code here
onSignIn = googleUser => {
this.toggleLoggedIn();
let user = googleUser.getBasicProfile();
let id_token = googleUser.getAuthResponse().id_token;
userName = user.getName(); //I try to grab the name from the user's account and assign it to userName
console.log('google user obj', user);
{/*console.log('google_id_token', id_token);*/}
console.log('Name:', userName); //This properly logs the correct userName to the console
};
// some other code here
render() {
console.log(this.state.isLoggedIn);
console.log(userName); //this incorrectly logs the userName lagged by one
// noinspection CheckTagEmptyBody
return (
<div>
<Login isLoggedIn={this.state.isLoggedIn} name={userName}/> //this passes the incorrect userName
<div id="my-signin2"></div>
<br />
{this.state.isLoggedIn && (
<button style={{ width: 200, height: 40, textAlign: 'center' }} onClick={this.logout}>
Logout
</button>
)}
</div>
);
}
}
Any help would be much appreciated.
My problem was the placement of this.toggleLoggedIn();
Moving it to the end of the onSignIn function block solved my problem.
onSignIn = googleUser => {
console.log("Sign in successful");
let user = googleUser.getBasicProfile();
userName = user.getName();
this.toggleLoggedIn();
};

React Router: Redirect logged in users to account if direct visit

I'd like logged in users who visit my home page by typing the url directly to be re-routed to their account, however I want them to be able to visit the homepage if they come from inside the app, what's the best way of doing this?
One way you can do this is to check the previous page that the user was on. So in your in your componentWillMount on your homepage React component, insert something like this:
import { Meteor } from 'meteor/meteor';
import { browserHistory } from 'react-router';
...
...
componentWillMount() {
if (Meteor.userId()) {
const referrer = document.referrer;
if (!referrer.includes('yoururl')) { // you can use Meteor.absoluteUrl() or example.com
browserHistory.push('/dashboard') // push whatever page you want
}
}
}
This will check to see if a user exists and where they came from. If the user exists and did not come from your site, they will go straight to /dashboard. Otherwise, the page will load as normal.

Resources