skip to Main Content

I am developing an application in React – Express – Mongo, how can i keep the user logged even after the browser is closed or page is refreshed?

5

Answers


  1. Assuming you have something like this:

    const MyComponent = () => {
       const [isLoggedIn, setIsLoggedIn] = useState(false);
       // your code
    }
    

    you could do something like this:

    const initialLoggedInState = localStorage.getItem('isLoggedIn') ?? false;
    const MyComponent = () => {
       const [isLoggedIn, setIsLoggedIn] = useState(initialLoggedInState === 'true');
       
       useEffect(() => {
          localStorage.setItem('isLoggedIn', isLoggedIn);
       }, [isLoggedIn]);
       // your code
    }
    
    Login or Signup to reply.
  2. A simple example for your understanding ,how to usage of localStorage,
    sessionStorage.

    https://www.geeksforgeeks.org/difference-between-local-storage-session-storage-and-cookies/

    // After hitting login button
    
    const handleSubmit = async e => {
      e.preventDefault();
      const user = { username, password };
      // send the username and password to the server
      const response = await axios.post(
        "http://blogservice.herokuapp.com/api/login",
        user
      );
      // set the state of the user
      setUser(response.data)
      // store the user in localStorage
      localStorage.setItem('user', response.data)
      console.log(response.data)
    };
    
    Login or Signup to reply.
    • create a jwt token in the login API call and return it when you log
      in as a response
    • store them in Cookies storage or local storage (I suggest using
      cookies)
    • check whether the token exists or not on the login page or signup
      page if it exists redirect the page to the login
    Login or Signup to reply.
  3. Store JWT Token in LocalStorage or Cookies. That’s the Simplest way.

    check out here – https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/

    Login or Signup to reply.
  4. const [isLoggedIn, setIsLoggedIn] = useState(false);
      
      useEffect(()=>{
       const localstorageGetInformation=localStorage.getItem('isLoggedIn')
        if(localstorageGetInformation=='1'){
          setIsLoggedIn(true)
        }
      },[])
    
      const loginHandler = (email, password) => {
        
        localStorage.setItem("isLoggedIn",'1')
        setIsLoggedIn(true);
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search