Reputation: 185
I am using React native to show the data from fetch API. But when the data update, it still shows the old data. I'm confusing how to do the pull down refresh inside my code.
class YourActivitiesScreen extends Component{
constructor(props) {
super(props);
this.state = {
activitiesList: [],
}
};
componentDidMount(){
AsyncStorage.getItem('id_token').then(this.getData)
}
getData=(token)=>{
console.log(token)
fetch('http://192.168.0.1:8887/api/auth/activities/your',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' +token,
},
})
.then((response) => response.json())
.then((res) => {
if(res.yourActivity)
{
let yourActivity = res.yourActivity
this.setState({activitiesList: yourActivity})
}
})
.catch((e) => console.log('Error: ', e))
}
renderItem = (item) => {
return (
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('Details',{activity: item})
}
>
<View style={styles.item}>
<Text style={styles.itemtext}>{item.name} </Text>
</View>
</TouchableOpacity>
);
}
render(){
const listActivities = this.state.activitiesList
return (
<View stlye={styles.container}>
<SafeAreaView>
<FlatList
data = {listActivities}
renderItem={({ item }) => this.renderItem(item)}
keyExtractor={item => item.id}
style={styles.list}
/>
</SafeAreaView>
</View>
)
}
}
Is that i need to do something to let the componentDidMount run again while I make a pull down action? If yes can someone explain to me how to do so?
Upvotes: 1
Views: 3485
Reputation: 37327
You must use the extraData
FlatList
prop each time you update the data.
extraData
A marker property for telling the list to re-render (since it implements
PureComponent
). If any of yourrenderItem
, Header, Footer, etc. functions depend on anything outside of thedata
prop, stick it here and treat it immutably.
Set extraData
prop with the activitiesList
object:
render(){
const listActivities = this.state.activitiesList
return (
<View stlye={styles.container}>
<SafeAreaView>
<FlatList
data={listActivities}
extraData={listActivities}
renderItem={({ item }) => this.renderItem(item)}
keyExtractor={item => item.id}
style={styles.list}
/>
</SafeAreaView>
</View>
)
}
Upvotes: 1
Reputation: 64
Please try to use onRefresh
prop in FlatList. Ref: https://reactnative.dev/docs/flatlist#onrefresh
Note: Please make sure to set the refreshing
prop correctly when use onRefresh
in FlatList.
Implement pull to refresh FlatList
Upvotes: 0