1

I'm trying to make a simple loader in react native and it gives me this error

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

my code:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import AnimatedLoader from 'react-native-animated-loader';


export default class Loader extends React.Component {
  constructor(props) {
    super(props);
    this.state = { visible: false };
  }

  componentDidMount() {
    setInterval(() => {
      this.setState({
        visible: !this.state.visible
      });
    }, 6000);
  }

  render() {
    const { visible } = this.state;
    return (
        <View backgroundColor={'black'} style={{ flex: 1, justifyContent:'center' }}>
      <AnimatedLoader
        visible={visible}
        overlayColor="white"
        source={require("./loader.json")}
        animationStyle={styles.lottie}
        speed={1}
      >
        <Text>Doing something...</Text>
      </AnimatedLoader>
      </View>
    );
  }
  
}


const styles = StyleSheet.create({
  lottie: {
    width: 100,
    height: 100
  }
});
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Cli Ad
  • 93
  • 8

1 Answers1

1

My only guess is that the component is unmounting before the timeout expires. Save a reference to the timer and clear it when the component is unmounting.

timerId = null;

componentDidMount() {
  this.timerId = setInterval(() => {
    this.setState(prevState => ({
      visible: !prevState.visible
    }));
  }, 6000);
}

componentWillUnmount() {
  clearTimeout(this.timerId);
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181