Trying and learning react.
In a React Component, Need to declare variable to access across multiple functions. Two approaches tried to achieve this - useState
(less good because of rendering) or let/var
. Example:
const [userName, setuserName] = useState(""); let root = "";
problem (part 1): on useEffect
after setting setuserName
hook I can not access userName
immediately. but after modifying root I can use the variable immediately. Example:
useEffect(() => { //get name from firebase doc ref... let name = user.claims.userName; //"AName" setuserName(name); root = name ; console.log("userName: " + userName+ " , " + root); //here userName is empty but root has the name. return () => { // db.ref("").off("value", listener); }; }, []);
problem (part 2): if both used in a function declared in the component problem part 1 reverses, I mean, the userName
(hook) will have name in it but the root variable will be empty. Example:
async function handleSubmit(e) { // e.preventDefault(); console.log("root = " + root + " , userName : " + userName );//here root is empty but userName has the name. return; //or call methods to firebase ref. }
Tested with assigning variables and state with string literals from code within (Eg: root = "testName"
). Just need a temporary variable to call firebase functions. Why this behaviour happens and what approach should I use here?
没有评论:
发表评论