I work with AWS-Amplify and want to get the owner from Cognito and assign it to the variable owner. When I do console.log(user.username)
inside then(
I see the right data. However, when I do console.log(owner);
I only see null.
function App() {
// Get user
let owner = null;
Auth.currentAuthenticatedUser({
bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
})
.then(user => {
owner = user.username;
})
.catch(err => console.log(err));
console.log(owner);
You don't want to do any side effects inside the component body and if you need to keep some kind of data that's changing over time state
is the place for it.
For side effect use useEffect
which can be configured when to fire the callback function using the dependencies array which in this case is empty and will fire the callback function only on mount
function App() {
const [owner, setOwner] = useState(null)
useEffect(() => {
Auth.currentAuthenticatedUser({
bypassCache: false,
})
.then((user) => {
setOwner(user.username)
})
.catch(console.log)
}, [])
return <div>{owner}</div>
}