2021年4月3日星期六

React JS component declare a variable required to use across multiple functions

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?

https://stackoverflow.com/questions/66937318/react-js-component-declare-a-variable-required-to-use-across-multiple-functions April 04, 2021 at 09:38AM

没有评论:

发表评论