Get Login User as Globally in around full React Project.

To set your login user id as global. So that you can access that from any other components. Especially it requires saving the user id as evidence for all Insert, Update, and Delete in your system.

Step 1: Set your login user id as global in your login controller or where you will write the login authentication code.

window.currentUser = currentUser;

Here currentUser is your variable name. Which variable name you will use here, use the exact name to access it.

Set variable as Global


Step 2: Now simply access that in any components.

Access from others components

Important: Access window.yourVariable by conditionally. Once it is null then set anything like - 'Unknown' or ' '. Otherwise, you may face an error once you would like to leave this component.




Code 👇

UserController.js
import User from "../models/User";

class UserController {
  async login(username, password, onSuccess, onError) {
    try {
      // Globaly assign current user
      const currentUser = new User(username);
      window.currentUser = currentUser;  

    } catch (err) {
      onError(err);
    }
  }
}
export default UserController;


AddCategoryPage.js
import React from 'react';

export default function AddCategoryPage() {

    const loginUser = window.currentUser ? window.currentUser.username : 'Unknown';
    console.log("userId : "+loginUser);
 
    }

Post a Comment

0 Comments