I'm trying to set set state variables and it seems to occur spottily at best. I tried putting in an async/await in react.useEffect, but the notes in the interpreter on the inspect console said to try that directly instead. so I try that on useState and useState's intellsense says "async has no effect on this method." How can I get my userInfo variable populated consistently so that I can use the value as intended?:
function Support() {
const [userInfo, updateInfo] = React.useState(null);
React.useEffect(() => {
Auth.currentAuthenticatedUser()
.then( currentUser => updateInfo({ userInfo: {name: currentUser.username, id: currentUser.attributes.sub }}))
.catch(err => console.log({ err }))
}, []);
return (
<div>
<div>Support</div>
<div>
username?: {userInfo.name}<br/>
User id?: {userInfo.id}
</div>
</div>
)
}
the browser complains about the attributes missing but I've seen them before sometimes when the response populates as intended. This is my current (unhelpful for me) stacktrace:
Here's what I've updated it to (still not working unfortunately):
return (
<div>
<div>Support</div>
<div>
username?: {userInfo.name ?? "Loading... "}<br/>
User id?: {userInfo.id ?? "Loading... "}
</div>
</div>
)
}
CodePudding user response:
Add dependency array to useEffect otherwise it'll be called frequently.
CodePudding user response:
function Support() {
const [userInfo, updateInfo] = React.useState({name: "" ,id: "" });
React.useEffect(() => {
Auth.currentAuthenticatedUser()
.then( currentUser => updateInfo({name: currentUser.username, id: currentUser.attributes.sub }))
.catch(err => console.log({ err }))
},[]);
return (
<div>
<div>Support</div>
<div>
Username : {userInfo.name} <br/>
User Id : {userInfo.id}
</div>
</div>
)
}
or
function Support() {
const [userInfo, updateInfo] = React.useState(null);
React.useEffect(() => {
Auth.currentAuthenticatedUser()
.then( currentUser => updateInfo({name: currentUser.username, id: currentUser.attributes.sub }))
.catch(err => console.log({ err }))
},[]);
return (
<div>
<div>Support</div>
<div>
Username : {userInfo.name? userInfo.name : ""} <br/>
User Id : {userInfo.id? userInfo.id : ""}
</div>
</div>
)
}
I think you can use one of these methods.