I am trying to pass some data into my FlatList component after running a graphql query. If I hard-code data using const DATA
it works. However, if I define two cases (successful query and unsuccessful query) and use let DATA
, the variables aren't passed into the FlatList properly and they are always undefined inside FlatList component.
How can I fix this? How can I ensure that DATA
is passed into the FlatList
only after the query has been run?
For example, hard coded data like this works:
const DATA = [ { id: '1', imageUrl: defaultUrl, name: 'Friend', vehicles: [], rating: 1, numberOfFriends: 3, }];
But this doesn't (query works fine though):
let DATA; const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('frineds', data.me.friends) DATA = data.me.friends.map( (item: { firstName: string; id: number; rating: number; vehicles: Array<Vehicle>; friends: Array<User>; }) => ({ id: item.id, imageUrl: defaultUrl, name: item.firstName, rating: item.rating, //vehicles: item.vehicles, vehicles: [], numberOfFriends: item.friends.length, }), ); }, onError: ()=> { DATA = [ { id: '1', imageUrl: defaultUrl, name: 'Friend', vehicles: [], rating: 1, numberOfFriends: 3, } } });
FlatList:
<FlatList showsHorizontalScrollIndicator={false} data={DATA} horizontal={true} //scrollEnabled renderItem={({ item }) => (<WhitelistItem title={item.name} face={item.imageUrl} firstName={item.name} rating={item.rating} numberOfFriends={item.numberOfFriends} vehicles={item.vehicles} /> )} keyExtractor={(item) => item.id} />
Edit:
I know about setStates but does this guarantee that every time the query re-runs, the data will be updated? Or do I necessarily have to use useEffect etc? In the past when I have used useStates, the data was often not updated automatically and kept giving old data so I was looking for an alternative way