Good day,
I'm working on a small react native project, I'm getting data from an API, but I noticed that every time I populate the state with data from the API, the mobile app becomes slow, and when I press the Touchable Opacity inside a child element of that Flatlist it takes around 5 seconds to respond.
//Don't worry it's all wrapped in a parent container
<View style={globalStyles.searchContainer}>
<TextInput style={globalStyles.textInput} placeholder="Who are you looking for? (e.g. Plumber)" onChangeText={setJob}/>
<TouchableOpacity style={globalStyles.searchButton} onPress={handleSearch}>
<Text style={globalStyles.text}>Search</Text></TouchableOpacity>
</View>
<FlatList
data={workers}
keyboardShouldPersistTaps="handled"
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={globalStyles.workerCard}>
<Image
style={globalStyles.thumbnail}
source={{uri: globalConfig.api_url + item.profile_picture}}
/>
<View style={globalStyles.workerDetails}>
<Text style={globalStyles.textDetails}>Name: {`${item.first_name} ${item.surname}`}</Text>
<Text style={globalStyles.textDetails}>Gender: {item.gender}</Text>
<Text style={globalStyles.textDetails}>Job: {item.job}</Text>
<Text style={globalStyles.textDetails}>Price: {`R${item.price}`}</Text>
<Text style={globalStyles.textDetails}>Transport fee: {`R${item.transport}`}</Text>
<Text style={globalStyles.textDetails}>Other Job: {(item.service1) ? item.service1 : ""} </Text>
<Text style={globalStyles.textDetails}>Other Job: {(item.service2) ? item.service2 : ""} </Text>
<Text style={globalStyles.textDetails}>Online: {(item.available) ? "Yes" : "No"} </Text>
<TouchableOpacity style={globalStyles.searchButton} onPress={() => bookWorker(item)}>
<Text style={globalStyles.text}>Book</Text>
</TouchableOpacity>
</View>
</View>
)}
/>
Add an "extraData" property to your flatList. This will tell your flatList to re-render on data changes. ( https://reactnative.dev/docs/flatlist#extradata )
<FlatList
data={workers}
keyboardShouldPersistTaps="handled"
keyExtractor={(item, index) => index.toString()}
extraData = {this.state.refreshing}
renderItem={({ item }) => ...
Here "this.state.refreshing" could be a boolean or an incremented integer that is updated each time you call the api.
Alternatively, and most recommended, you could add a onRefresh property and move your api calls there. ( https://reactnative.dev/docs/flatlist#onrefresh ). This would handle all the flatList changes for you once you update your "workers" array.
I figured it out, there was a function that was being called somewhere in the component, I removed it and now it's working just fine.
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.