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
Edit: I miss understood what u wan’t sorry try this
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.