I've trying to implement simple updates in a function component in react and seem to have stumbled onto some basic logical errors on my part. Can you help?
My code :
import React, { useState } from "react";
import "./App.css";
var timeout; // this variable wasn't scoped inside the function?.
function App() {
const [name, setUserName] = useState("");
const [password, setUserPassword] = useState("");
const [showHackMessage, setShowHackMessage] = useState(false);
const enterUserName = e => {
console.log(e.target.value);
setUserName(e.target.value);
};
const enterUserPassword = (e) => {
console.log(e.target.value,timeout);
setUserPassword(e.target.value);
if (e.target.value.length > 0) {
timeout= setTimeout(()=>setShowHackMessage(true), 1000);
console.log(timeout);
/// Why did not timeout= setTimeout(setShowHackMessage(true), 5000); work? is setShowHackMessage not a function?
// timeout();
}
else if(e.target.value.length===0) {
console.log("Tricky user!");
console.log(timeout,'L29>>');
//not working perfectly!
clearTimeout(timeout);
setShowHackMessage(false);
}
};
return (
<div className="App">
<p>Login-Hacker</p>
<input name={"email"} onChange={enterUserName}></input>
<br></br>
<br></br>
<input name={"password"} onChange={(e)=>enterUserPassword(e)}></input>
<p>Powered by Saurabh</p>
{name.length > 0 && <p>Your name is {name}</p>}
{password.length > 0 && <p>Your password is {password}</p>}
{showHackMessage && <p className='awesome'>Now you are hacked!</p>}
</div>
);
}
export default App;
So my first question would be:-
Why do i have to use callback while defining a setstate function in settimeout? I tried
timeout= setTimeout(setShowHackMessage(true), 1000); and it didn't work, while
timeout= setTimeout(()=>setShowHackMessage(true), 1000); works perfectly. Is setShowHackMessage (in useState not a function?)
If i define the variable var timeout inside the function, the cleartimeout doesn't work(shows as undefined in console), but works perfectly if i define it outside the function, as in the code. Is the whole function "rendered" after setstate( hence losing previous instance of variable timeout?).Should i have used refs for this?
Thank you.
useEffectfor that ... 1) you already called func, not defined func to be called