how do I setInterval in react native?

Viewed 1533

I want to setInterval to the following viewfor 30s how do I do that ?

    import React, {PureComponent} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, Animated,ProgressBarAndroid} from 'react-native';
import {RNCamera} from 'react-native-camera';
import Icon from 'react-native-vector-icons/Entypo';
import ImagePicker from 'react-native-image-crop-picker';
import Video from 'react-native-video';
let animation = new Animated.Value(0);

export default class Shoot extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      recording: false,
      processing: true,
      upload: false,
      galleryVideo: '',
      progress: '',
      video: '',
    };
  }
  render() {
    return (
      <View style={styles.container}>
        {this.state.upload == true && (
          <TouchableOpacity
            style={{
              backgroundColor: '#e75480',
              position: 'absolute',
              width: 80,
              height: 30,
              zIndex: 2,
              padding: 5,
              borderRadius: 5,
              right: 0,
              justifyContent: 'center',
              alignContent: 'center',
            }}
            onPress={() => this.props.navigation.navigate('Post', {key: 1})}>
            <Text style={{color: 'white', textAlign: 'center'}}>Next</Text>
          </TouchableOpacity>
        )}

        {this.state.upload == false && (
          <TouchableOpacity
            style={{
              position: 'absolute',
              bottom: 0,
              right: '15%',
              justifyContent: 'center',
              alignItems: 'center',
            }}
            onPress={this.video.bind(this)}>
            <Icon name="image" size={30} color="white" />
            <Text style={{color: 'white', fontWeight: 'bold'}}>Upload</Text>
          </TouchableOpacity>
        )}

        <TouchableOpacity
          onPress={this.take60sVideo.bind(this)}
          style={{
            width: 60,
            height: 60,
            justifyContent: 'center',
            alignContent: 'center',
            position: 'absolute',
            bottom: 0,
            left: '25%',
          }}>
          <Text style={{textAlign: 'center', color: 'red', fontSize: 15}}>
            60s
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={this.take15sVideo.bind(this)}
          style={{
            width: 60,
            height: 60,
            justifyContent: 'center',
            alignContent: 'center',
            position: 'absolute',
            bottom: 0,
            left: '5%',
          }}>
          <Text style={{textAlign: 'center', color: 'red', fontSize: 15}}>
            15s
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={this.take30sVideo.bind(this)}
          style={styles.capture}></TouchableOpacity>
      
        {this.state.progress === true && (
          <View
            style={{
              borderColor: '#0000FF',
              borderWidth: 1,
              width: '100%',
              height: 15,
              top: 0,
              position: 'absolute',
              bottom: 0,
              zIndex: 2,
            }}>
            <Animated.View
              style={
                ([StyleSheet.absoluteFill],
                {backgroundColor: '#8BED4F', width: '50%', height: 10})
              }
            />
            {/* <ProgressBarAndroid styleAttr="Horizontal"/> */}
          </View>
        )}
        {this.state.video == '' ? (
          <RNCamera
            ref={(ref) => {
              this.camera = ref;
            }}
            style={styles.preview}
            type={RNCamera.Constants.Type.back}
            flashMode={RNCamera.Constants.FlashMode.on}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            captureAudio={true}
          />
        ) : (
          <Video
            source={{uri: this.state.video}}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              alignItems: 'stretch',
              bottom: 0,
              right: 0,
              height: '90%',
            }}
            resizeMode="cover"
            repeat={true}
          />
        )}
      </View>
    );
  }
  video = () => {
    ImagePicker.openPicker({
      mediaType: 'video',
    }).then((video) => {
      this.setState({
        galleryVideo: 1,
        video: video.path,
        upload: true,
      });
    });
  };

  take30sVideo = async () => {
    if (this.camera) {
      try {
        const options = {
          quality: 2,
          videoBitrate: 8000000,
          maxDuration: 30,
        };
        const promise = this.camera.recordAsync(options);
        this.setState({progress: true});

        if (promise) {
          this.setState({recording: true});
          const data = await promise;
          this.setState({recording: false, upload: true});
          console.log(data);
          console.log('upload', this.state.upload);
        }
      } catch (error) {
        console.log(error);
      }
    }
  };
  take60sVideo = async () => {
    if (this.camera) {
      try {
        const options = {
          quality: 2,
          videoBitrate: 8000000,
          maxDuration: 60,
        };
        const promise = this.camera.recordAsync(options);

        if (promise) {
          this.setState({recording: true, upload: true});
          const data = await promise;
          this.setState({recording: false});
          console.log(data);
        }
      } catch (error) {
        console.log(error);
      }
    }
  };
  take15sVideo = async () => {
    if (this.camera) {
      try {
        const options = {
          quality: 2,
          videoBitrate: 8000000,
          maxDuration: 15,
        };
        const promise = this.camera.recordAsync(options);
        if (promise) {
          this.setState({recording: true});
          const data = await promise;
          this.setState({recording: false, upload: true});
          console.log(data);
        }
      } catch (error) {
        console.log(error);
      }
    }
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  preview: {
    height: '90%',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  capture: {
    backgroundColor: '#e75480',
    borderRadius: 40,
    borderWidth: 3,
    borderColor: 'red',
    width: 60,
    height: 60,
    position: 'absolute',
    bottom: 0,
    justifyContent: 'center',
    left: '45%',
    alignContent: 'center',
  },
});

say,I want the view the progress to be true once recording is started,that take30svideo() is triggered,once that is true the component should animate to show the progress and then stop as soon as the timer gets done,above is the complete code,I hope this helps

Any suggestions would be great

2 Answers

You need to save the time as an instance variable and clear it on component unmount or else it'll keep running even after it unmounts like below

componentDidMount() {
  this._interval = setInterval(() => {
    // Your code
  }, 1000);
}

componentWillUnmount() {
  clearInterval(this._interval);
}

I am assuming this layout you want to show for 30 second as app mounted. You can do something like this:

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      progress: true,
    };
  }
  timer;

  componentDidMount() {
    this.timer = setInterval(() => {
      this.setProgress();
    }, 30000);
  }

  setProgress = () => {
    this.setState({
      progress: false ,
    });
  };
  componentWillUnmount(){
  if(this.timer) clearInterval(this.timer);
 }

  render() { 
      if(this.state.progress){
       <View
            style={{
              borderColor: '#0000FF',
              borderWidth: 1,
              width: '100%',
              height: 15,
              top: 0,
              position: 'absolute',
              bottom: 0,
              zIndex: 2,
            }}>
            <Animated.View
              style={
                ([StyleSheet.absoluteFill],
                {backgroundColor: '#8BED4F', width: '50%', height: 10})
              }
            />
          </View>
      }
    else{
       ... rest of your code
     }
   }
    
}

Related