So Im having trouble using a variable that is assigned with the useState hook from react-native. Here is my code.
import { SafeAreaView } from "react-native-safe-area-context";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useState } from "react";
import FlatButton from "../ui/FlatButton";
import { COLORS } from "../../constants/styles";
import { getPreSignedUrl } from "../../utils/storage";
import IconButton from "../ui/IconButton";
import { leaveCommunity } from "../../utils/community";
import { getCommunityUserByCommunityId } from "../../utils/community";
import { currentSession } from "../../utils/auth";
function CommunityDetails({ community }) {
const navigation = useNavigation();
const [statistics, setStatistics] = useState(false);
const [coverPicture, setCoverPicture] = useState('');
const [communityUser, setCommunityUser] = useState('');
const [userId, setUserId] = useState('');
useEffect(() => {
getMyId();
getCoverPicture();
navigation.setOptions({
headerTitle: '',
headerBackTitle: 'Back',
headerRight: ({ tintColor }) => (
<IconButton
icon="close"
size={24}
color={tintColor}
onPress={handleLeaveCommuntiyAlert}
/>
),
});
}, []);
useEffect(() => {
handleCommunityUser();
}, [userId]);
useEffect(() => {
console.log('Community user:', communityUser);
}, [communityUser]);
async function getMyId() {
try {
const userInfo = await currentSession();
const userName = userInfo.idToken.payload['cognito:username'];
console.log('My user id: ' + userName);
setUserId(userName);
} catch (error) {
console.log('Error fetching user information: ' + error);
}
}
async function handleCommunityUser() {
try {
const communityUserResponse = await getCommunityUserByCommunityId(community.id);
const communityUsers = communityUserResponse.data.communityUsersByCommunityId.items;
console.log('Community users:', communityUsers);
const user = communityUsers.find(user => user.userId == userId);
console.log('User found:', user);
if (user) {
console.log('User ID:', user.id);
setCommunityUser(user.id);
} else {
console.log('No user found for the current user ID');
setCommunityUser(null);
}
} catch (error) {
console.log('Error fetching community users:', error);
}
}
async function handleLeaveCommuntiyAlert() {
Alert.alert('Are you sure you want to leave this community? btw this is your communityId: '+communityUser, '', [
{ text: 'Yes', onPress: handleLeaveCommuntiy },
{ text: 'No', onPress: () => console.log('Cancel') }
]);
}
async function handleLeaveCommuntiy() {
console.log('Leaving community with this id:', communityUser);
if (!communityUser) {
console.log('Community user is not set. Cannot leave community.');
return;
}
const leavedCommunity = await leaveCommunity(communityUser);
navigation.navigate('Community', { all: true });
console.log(leavedCommunity);
}
async function getCoverPicture() {
console.log('Getting cover picture');
const file = await getPreSignedUrl(community.coverPicture, 'guest', userId);
setCoverPicture(file.url);
}
function handlePosts() {
setStatistics(false);
}
function handleStatistics() {
setStatistics(true);
}
return (
<SafeAreaView style={styles.container}>
<View>
<Text style={styles.title}>{community.name}</Text>
</View>
<ScrollView>
<View style={styles.communityHeader}>
<Text>Here comes the header</Text>
<Button onPress={getCoverPicture} title="Get cover picture" />
</View>
<View>
<View style={styles.filterContainer}>
<View>
<FlatButton onPress={handlePosts}>Posts</FlatButton>
<View style={!statistics ? styles.selectedTab : styles.notSelectedTab}></View>
</View>
<View>
<FlatButton onPress={handleStatistics}>Statistics</FlatButton>
<View style={statistics ? styles.selectedTab : styles.notSelectedTab}></View>
</View>
</View>
<View>
<Text>Here comes the content</Text>
<Text>This is my community user ID: {communityUser}</Text>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
title: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
filterContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 20,
marginBottom: 20,
},
selectedTab: {
width: '30%',
borderBottomColor: 'black',
borderBottomWidth: 2,
alignContent: 'center',
alignItems: 'center',
marginHorizontal: '35%',
},
notSelectedTab: {
width: '30%',
alignContent: 'center',
alignItems: 'center',
marginHorizontal: '35%',
},
communityHeader: {
height: 200,
},
image: {
width: 100,
height: 100,
},
});
export default CommunityDetails;
So the problem is with the communityUser
as you see in the code I can print it in my component but when I try to leave in the alert box you can see that it should also print it but this never happens. I find this weird as I can print the Id inside the component. Anyone have an idea why this is happening. Thanks in advance