So I am trying to pull a users friendsList from a dynamoDB. I am using an GraphQL API to access my DB. In the commented out section of the code provided there I mention I have tried users[1].friends.map, which does return the correct friends list array, but users does not seem to get set until after the friends list has been rendered. How should I set up my code so the correct friends list (found in users) gets rendered the first time the page is rendered rather than after it gets updated??
const FriendsList = [
{
name: 'Name 1',
},
{
name: 'Name 2',
},
{
name: 'Name 3',
},
{
name: 'Name 4',
},
{
name: 'Name 5',
},
{
name: 'Name 6',
},
];
const Friends = (props) => {
const [refreshing, setRefreshing] = React.useState(false);
const [users, setUsers] = React.useState([]);
const [formData, setFormData] = React.useState(initialFormState);
React.useEffect(() => {
fetchUserData();
}, []);
async function fetchUserData() {
const userData = await API.graphql({ query: listUsers });
setUsers(userData.data.listUsers.items);
}
//console.log(users);
const renderFriendsList = (props) => {
/*
*Here I want to have something like...
* return users[1].friends.map((item, i) => {
* so I can iterate through the friends list
*/
return FriendsList.map ((item, i) => {
return (
<View style={{ paddingLeft: scale(10), paddingRight: scale(10) }}>
<View
style={{
backgroundColor: '#d1cfcf',
width: scale(330),
height: scale(85),
borderRadius: scale(10),
flexDirection: 'row',
borderColor: '#8f8a8a',
borderBottomWidth: 1,
}}>
<View>
<Text style={{ fontSize: 15 }}>{item.name}</Text>
</View>
</View>
</View>
);
});
};
return (
<View style={{}}>
<View style={{ marginTop: scale(5) }}>
{renderFriendsList()}
</View>
</View>
);
}
fetchUserData() should set users to the user data, but when I call users before the first time it renders, users is still undefined. If the application is running and has rendered the friends list from friendsList, and then I change it to users1.friends on the fly, it works, but that is obviously is an issue because it does not render correctly the first time. I use the React.useEffect() and I figured that would call fetchUserData() when the page is rendered.
Here is the output I am getting when I console.log(users.result)