Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2613

React native sensor data retrieval unmounted comp. warning

I am building an app that can get the speed of my cell phone every time I move it. I get updates to this value but also I can see the next warning:

"Warning: 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."

Why is this happening?

The code I am using is:

import React from 'react';    
import {
    Text
  } from 'react-native';

import {
    accelerometer,
    gyroscope,
    setUpdateIntervalForType,
    SensorTypes
  } from "react-native-sensors";

import { map, filter } from "rxjs/operators";    

export class SpeedPanel extends React.Component{    
    constructor(props) {
        super(props);
        this.state = { 
            speed: 0,
            subscription: accelerometer
        }
    }

    getData = () => {
        const self = this;
        const subscription = this.state.subscription
        .pipe(map(({ x, y, z }) => x + y + z), filter(speed => speed > 10))
        .subscribe(
          speed => {
                     self.setState({speed: speed})
                     console.log(`You moved your phone with ${speed}`) 

                    },    
          error => {
            console.log("The sensor is not available");
          }
        );

        setTimeout(() => {
            // If it's the last subscription to accelerometer it will stop polling in the native API
            subscription.unsubscribe();
          }, 1000);          
  
    }    

    componentDidMount() {
        setUpdateIntervalForType(SensorTypes.accelerometer, 400); // defaults to 100ms
  
        setInterval(this.getData, 400);
    }

    render () {
        return(
            <Text>
                {'Hello \n'}
                {this.state.speed}
            </Text>
        )
    } 


}

Upvotes: 0

Views: 199

Answers (1)

Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2613

Not to worry... I reloaded this app and no more warnings show up.

Upvotes: 0

Related Questions