React Native FlatList ListEmptyComponent always showing even if not empty - react-native

I'm browsing through StackOverflow in search of someone experiencing my same issue, however couldn't find much. I'm fetching flatlist data from backend and i need the empty text placeholder component to disappear when flatlist is not empty, however it always stays there and never disappears even when data is correctly fetched in the flatlist. How can i solve this?
Ps. When assigning dummy data to the flatlist, this issue does not happen.
<FlatList
ListEmptyComponent={() => (<Text style={styles.emptyListText}>No upcoming trips to show.</Text>)}
data={trips}
renderItem={({ item }) => <MyTripsPostItem post={item} onPress={() => navigation.navigate("Post Screen")}
/>}
/>

What I do is that I check if the query is loading and if it is not then I show my View ListEmptyComponent.
ListEmptyComponent={
!isLoading && (
<View style={styles.containerEmptyList}>
// things
</View>
)
}
I use react-query which provide a "isLoading" variable but you can do the same in your function query with useState
Edit : Also the function () => is not needed for that props.

Use trips.length instead of trips.
// checks if trips size is more than 0
!trips.length && <ListEmptyComponent />
while
// checks if trips is undefined or null
trips && <ListEmptyComponent />
In your case, I presume you set a default value to trips which is an empty array / [], so, it wasn't undefined or null.

Related

Return JSX Is Not Updating On State Change From Some Reason

So like the title states I have it setup so that I want to display a loading text or something simple while I wait for my array to get loaded up with data from a local array.
I have a simple array at the top of my class with Name, Id and Image. I than load these into an array I called items and load into another array called random items.
When I run the code normally nothing gets displayed due to the array being empty. I understand that and have tried to create this workaround but does not appear to be working.
return (
<LinearGradient colors={["#FF8A8A", "#DC143C"]} style={{ flex: 1 }}>
<View>
{dataLoaded ? (
<View>
<Text>Loading...</Text>
</View>
) : (
items.map((item, i) => {
<MatchingDisplay
key={i}
listItem={item}
randItem={randItems[i]}
checkChoice={checkChoice}
/>;
})
)}
</View>
</LinearGradient>
);
After my function runs and the array is loaded up I make a state change to dataLoaded and change it to the boolean value True. For some reason my return method is not updating and displaying the items mapped out using the MatchingDisplay component.
I am not using any asynchrous functions as from what I understand it should just update automatically.
Any and all help is appreciated thanks!
Your conditional is flipped.
When dataLoaded is false, the empty array is displayed. When it’s true, the loading text is displayed. Flipping this to !dataLoaded should fix the issue.

Why is data from useQuery undefined when I start screen?

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

How to dinamically update the value coming from useAnimatedStyle - Reanimated 2

Say that I have a component where I create child components based on the number of elements passed from the parent ( think of it as a page indicator, for example ).
What I would like to do, is to animate the transition between these dots (their backgroundColor) depending on which one is active.
I have tried in a few ways to match the current value to the index of the child element, however, since I don't have the index beforehand, my attemps have failed.
I am posting the basic component down there without my fail attemps to animate it so it illustrates better what I am talking about.
How would one go about doing that in reanimated 2?
const component = ({active, amountOfDots}) => {
const dotsArray = Array(amountOfDots).fill(0);
return (
<View style={{}}>
{dotsArray.map(() => {
return <Animated.View style={{}} />;
})}
</View>
);
};

How do I refresh the page with an onPress in ReactNative

I am new to ReactNative and have encountered an issue regarding page refreshing. I have some filters in my screen and will like the page to refresh once any of these filters are pressed, but am unable to find any guides on how to do so. I have searched endlessly but only found numerous guides on refreshing with pulldown, and I feel like the solution has something to do with React.useEffect but am unfamiliar with that.
The important parts of my code are as below:
The TouchableOpacity component to trigger the refresh:
<TouchableOpacity
style={styles.filterButton}
onPress={() => {
sortByRating()
}}
>
where sortByRating() is a function to sort my eateriesToShow array based on their ratings.
The FlatList I want to be refreshed on filter:
<FlatList
data={eateriesToShow}
keyExtractor={item => item.id.toString()}
renderItem={renderItem}
showsVerticalScrollIndicator={true}
/>
</View>
)
}
Currently my eateriesToShow array gets sorted, but the FlatList does not get refreshed. Any help will be appreciated.
You want your flatist to update when the data is changed. refreshing your flautist is another thing. So what I suggest you to do is use the useState hook.
const [yourList, setYourList] = useState<string | null>(null)
like this (you don't need the types if you are using javascript instead of typescript)
and then when sorting by rating you should do setYourList(newEateriesArray)
and your flautist should update.

react-naitve, how to move to certain item in flatlist

I am making my own app using react-native
I have some difficulties to do notice function.
We have board and comments, if we get notice that someone writes comment, I want to go to that comments in flatlist comments (there can be many comments in board, so if we just go to board without focusing notice comments, user may be hard to find comments). I searched some example of scrollindex method in flatlist. But I want to go directly without button or input. We have comment id in notice model. So first I think that if we compare comment id in flatlist and set state, we can save index of that comments. But setState() doesn't work in flatlist because of error "cannot update a component from inside the function body of a different component."
And second, i don't know where we put the function scrollToIndex() because it may move after rendering is finished. But i don't know that state.
IF you know how to solve that problem pleases help me!!
(you can think instagram comment notice, if we click them , we can see that comment, no matter where they were, becauses it automatically move to that comments
getItemLayout = (data, index) => (
{ length: 50, offset: 50 * index, index }
)
getColor(index) {
const mod = index%3;
return COLORS[mod];
}
scrollToIndex = () => {
let randomIndex = Math.floor(Math.random(Date.now()) * this.props.data.length);
this.flatListRef.scrollToIndex({animated: true, index: randomIndex});
}
<FlatList
style={{ flex: 1 }}
ref={(ref) => { this.flatListRef = ref; }}
keyExtractor={item => item}
getItemLayout={this.getItemLayout}
initialScrollIndex={50}
initialNumToRender={2}
renderItem={({ item, index}) => (
<View style={{...style, backgroundColor: this.getColor(index)}}>
<Text>{item}</Text>
</View>
)}
{...this.props}
/>
It is is simple code that use scrolltoindex. It can move to random index item
But I want to move certain item doing switch screen. In noticescreen, if we click notice , we need to move board that have that comments. Then we scroll to the comments to show user. We have board id and comments id in notice model. It is not hard to move to the board. But scroll to the comments is hard to me. Any solution?? please