Search code examples
react-nativesetintervalreact-native-flatlisttouchableopacity

React Native touchable opacity fails inside a flatlist during setInterval


I have a FlatList where all of the items are TouchableOpacities and they each have an onClick function that worked just fine until I added a Slider which automatically slides over time from the setInterval function. Here is what this page of the app looks like (the song titles are TouchableOpacities):
enter image description here

Here are the important parts of code for this issue:

<FlatList
      data={queueItems}
      renderItem={renderItem}
      keyExtractor={item => Math.floor(Math.random() * 1000000).toString()}
 />
const renderItem = ({ item }) => {
    return(
        <dataContext.Consumer>
        {({ setModalVisible }) => (
             <TouchableOpacity onPress={() => {setModalVisible(true, item)}} style={styles.QueueContainer}>
                  <Text style={styles.text}>{item.title}</Text>
             </TouchableOpacity>
        )}
        </dataContext.Consumer>
    );
}
<Slider
    value={playSeconds} maximumValue={duration}
    onSlidingStart={value => onSliderEditStart()}
    onSlidingComplete={value => onSliderEditEnd(value)}
    maximumTrackTintColor='gray'
    minimumTrackTintColor='blue'
    thumbTintColor='white' 
    style={{flex:1, alignSelf:'center'}}
 />
        async componentDidMount(){
            setInterval(() => { if(this.sound && this.sound.isLoaded() && !this.sliderEditing){
                this.sound.getCurrentTime((seconds) => {
                    this.setState({playSeconds:seconds});
                })
            }}, 100);
        };
        this.onSliderEditStart = () => {
            this.sliderEditing = true;
            console.log('start');
        }
        this.onSliderEditEnd = (value) => {
            if(this.sound){
                this.setState({
                    playSeconds: value,
                });
                this.sound.setCurrentTime(value);
            }
            this.sliderEditing = false;
            console.log('end');
        }

I know the issue has to do with setInterval because the onPress function works when I take the setInterval out of the code. Also, I tried changing the setInterval to 5 seconds, and the onPress would work at any time except for the 5-second interval. The issue also must have something to do with the FlatList because the TouchableOpacities outside of the FlatList work just fine.


Solution

  • SOLVED The issue was that generating keys for each item in the flatlist using:

    keyExtractor={item => Math.floor(Math.random() * 1000000).toString()}
    

    For some reason generating keys this way is very glitchy.