I am using flatlist to render data from api, the data are rendered and also displayed. But the problem is the items are displayed multiple times. I got 5 items from the api but those 5 items are repeating.
I have implemented as follows:
export default class FlatSpeakers extends Component {
constructor(props) {
super(props);
this.state = { isLoading: true, data: [] }
}
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(res => {
this.setState({
isLoading: false,
data: res.data,
})
})
}
renderItem() {
return (
this.state.data.map(item =>
<SpeakersDetails key={item.title} speakerD={item} />
)
)
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem.bind(this)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
I have implemented the SpeakersDetails component as follows:
const SpeakersDetails = ({ speakerD }) => {
const { title, artist, thumbnail_image, image, url } = speakerD;
const {
thumbnailStyle,
headerContentStyle,
thumbnailContainerStyle,
headerTextStyle,
imageStyle
} = styles;
return (
<Card>
<CardSection>
<View style={thumbnailContainerStyle}>
<Image
style={thumbnailStyle}
source={{ uri: image }}
/>
</View>
<View style={headerContentStyle}>
<Text style={headerTextStyle}>{title}</Text>
<Text>{artist}</Text>
</View>
</CardSection>
</Card>
);
};
FlatList
iterates over data
and call renderItem
for each item in it, you are rendering the full list at every call, that's why you get items duplicated.
renderItem
receives the current item as parameter, try change your function like this:
renderItem({item}) {
return (
<SpeakersDetails key={item.title} speakerD={item} />
)
}
Check the renderItem
documentation for further details, including additional parameters this function receives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With