When I start screen, I get data from useQuery
And by using useEffect
, I get data and immediately sort this data.
After sorting data, I put this data to useState
named flatlistdata.
And I draw screen by using Flatlist with this data. Flatlist data should be sorted.
So I need to refined data before.
const { data: allFeedData, refetch: allFeedRefetch } = useQuery(SEE_ALL_FEED_ORDER);
const [flatlistdata, setFlatlistdata] = useState([]);
useEffect(() => {
allFeedRefetch();
setFlatlistdata(
[...allFeedData.seeAllFeedOrder].sort(function (a, b) {
return b.directFeedNumber - a.directFeedNumber;
})
);
}, []);
<FlatList
data={flatlistdata}
keyExtractor={(item) => item.id}
renderItem={RankRow}
refreshing={refreshing}
onRefresh={refresh}
/>
However when I click screen, it says undefined is not an object
which means data is empty.
I think the problem here is that screen is drawn, before sorting data and putting it to useState...?
I need a little hint 😠Please help me.
The query is an asynchronous operation, so, the data
variable will always start out as undefined while the network request completes. There are two possible solutions.
In your useEffect, only set your state if data
is defined. Wrap your setFlatlistData with if (allFeedData?.length) { ... }
Use the React Query selection
prop to have Query do the same operation before allFeedData
gets populated. Check the select
prop in the docs for useQuery: https://react-query-v2.tanstack.com/reference/useQuery