I am developing an app with React-native, and I am using AWS Amplify as the backend for it. I want to get the currently authenticated user's Id and register it as a state variable. My code is:
const [userId, setUserId] = useState("");
// set AuthUserId
useEffect(() => {
let isMounted = true;
const setAuthUserId = async () => {
try {
const userInfo = await Auth.currentAuthenticatedUser();
const id = userInfo.username;
isMounted && setUserId(id);
console.log("userId: ", userId);
} catch (err) {
console.log("Failed to catch the AuthUser Id", err);
}
return () => {
isMounted = false;
};
};
setAuthUserId();
}, []);
The way I expect it to work is that at first userId is set to an empty string as its default value. Then in the async method, it waits for the promise to be resolved, and after it is resolved sets my state variable which will cause the component to re-render this time with the userId stored in my state variable. But what happens is that the state variable is set to an empty string and the component does not re-render.
I am kind of new to React-native and AWS Amplify, and it is a big help if you let me know what is going wrong. Thank you.