I run a graphql query and depending on the data, render a flatList.
const { data, error } = useGetMyProfileQuery({
//onCompleted: _onCompleted,
onError: _onGetMyProfileQueryError,
});
....
return (
<SafeAreaView style={styles.safeView}>
<Container style={styles.container}>
<View style={styles.listHolder}>
<FlatList
data={data ? data.me.friends : null}
horizontal={false}
renderItem={({ item }) => (
<Friend
friend={item}
onDeleteFriend={onDeleteFriend}
originatorId={data ? data.me.id : null}
/>
)}
keyExtractor={(data: any) => '3'}
ListEmptyComponent={renderEmptyContainer()}
/>
</View>
</Container>
</SafeAreaView>
);
};
However, currently, I have to use ternary operators for checks like data? data.me.friends: null
data? data.me.friends: null
in the FlatList
to avoid Typescript errors. If the query fails, and the data is null, It disturbs the whole performance and I will have to use multiple if-else within the whitelist item component too.
So I am looking for the best way such that data is passed into the Flatlist only when the mutation is successful. I could use onCompleted
for that but I am not sure how to organize it such that no flat list is displayed from the main return when there's an error.
Also, currently, I am using the same key for all elements of the list but it shouldn't be like that obviously
Render your list when you have data, In this way, you will also have better performance when lesser things are rendered so it will be a conditional rendering of your Flatlist
.
{data && data.me && data.me.friends.lenght > 0 &&
<FlatList
data={data.me.friends}
horizontal={false}
renderItem={({ item }) => (
<Friend
friend={item}
onDeleteFriend={onDeleteFriend}
originatorId={data ? data.me.id : null}
/>
)}
keyExtractor={(data: any) => '3'}
ListEmptyComponent={renderEmptyContainer()}
/>
}
Did you tried data={data?.me?.friends}
You can also use this syntax data={data? data?.me?.friends: []}
data={data? data?.me?.friends: []}
You have to used as
<SafeAreaView style={styles.safeView}>
<Container style={styles.container}>
<View style={styles.listHolder}>
<FlatList
data={data?.me?.friends || []}
horizontal={false}
renderItem={({ item }) => (
<Friend
friend={item}
onDeleteFriend={onDeleteFriend}
originatorId={data ? data.me.id : null}
/>
)}
keyExtractor={(data: any) => '3'}
ListEmptyComponent={renderEmptyContainer()}
/>
</View>
</Container>
</SafeAreaView>
data={data?.me?.friends || []} you have to use this that I have already mentioned in the code https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining This link will also useful
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.