Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatlist displaying same items multiple times

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.

enter image description here

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>
);
 };
like image 798
Nabin Dhakal Avatar asked Sep 18 '25 04:09

Nabin Dhakal


1 Answers

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.

like image 179
bug Avatar answered Sep 21 '25 12:09

bug