skip to Main Content

I have a button that, when clicked, should say WELCOME USER. Additionally, I want to store whether the user has clicked the button in localStorage so on subsequent page loads I can tell if they’ve clicked the button. If the user hasn’t yet clicked the button and the value is not set in local storage, we should not show the text WELCOME USER.

import { useState } from "react";

function App(){
  let [isLogin,setIsLoging] = useState(false)
  localStorage.setItem("isLogin",false)

  if (localStorage.getItem("isLogin") == "true") {
    return (
      <>
        <h1>Welcome user</h1>
      </>
    );
  } else {
    return (
      <>
        <button onClick={login}>login</button>
      </>
    );
  }

  function login(){
    setIsLoging(isLogin = true)
    localStorage.setItem("isLogin", true)
  }
}
 
export default App;

2

Answers


  1. Edit: I miss understood what u wan’t sorry try this

    import { useState } from "react";
    
    function App() {
      const [isLogin, setIsLoging] = useState(localStorage.isLogin ? true : false);
      return (
        <>
          {isLogin ? (
            <h1>Welcome User </h1>
          ) : (
            <button onClick={login}>login</button>
          )}
        </>
      );
      function login() {
        setIsLoging(true);
        if(!localStorage.isLogin)
          localStorage.isLogin = true;
      }
    }
    export default App;
    
    Login or Signup to reply.
  2. You are calling the setter of useState wrong. It should be setIsLogin(true). Also you are setting the value false on the beginning of every render cycle, so it will never be true… You should be putting calls to localStorage into a useEffect, to not do it on every rerender.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search