React Native: undefinded is not an object - Using Expo Sensors / Barometer

Hello everyone, first of all I’m new to the forum and hope to get help with the following issue, as a beginner:

  1. SDK Version: 38
  2. Platforms(Android/iOS/web/all): Android (iOS untested)

Working with the Barometer Sensor

Using the Example Code from the Expo documentation is causing an error after doing little changes. While the Barometer works on App launch perfectly it is causing an Type Error after changing or saving code:

TypeError: undefined is not an object (evaluating ‘_this_subscription’)

This is the Code from the Expo Documentation:

import React, { useState, useEffect } from 'react';
import { Text, TouchableOpacity, View, Platform } from 'react-native';
import { Barometer } from 'expo-sensors';

export default function App() {
  const [data, setData] = useState({});

  useEffect(() => {
    _toggle();
  }, []);

  useEffect(() => {
    return () => {
      _unsubscribe();
    };
  }, []);

  const _toggle = () => {
    if (this._subscription) {
      _unsubscribe();
    } else {
      _subscribe();
    }
  };

  const _subscribe = () => {
    this._subscription = Barometer.addListener(barometerData => {
      setData(barometerData);
    });
  };

  const _unsubscribe = () => {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  };

  const { pressure = 0, relativeAltitude = 0 } = data;

  return (
    <View style={styles.sensor}>
      <Text>Barometer:</Text>
      <Text>Pressure: {pressure * 100} Pa</Text>
      <Text>
        Relative Altitude:{' '}
        {Platform.OS === 'ios' ? `${relativeAltitude} m` : `Only available on iOS`}
      </Text>
      <View style={styles.buttonContainer}>
        <TouchableOpacity onPress={_toggle} style={styles.button}>
          <Text>Toggle</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

Source: Expo Docs: https://docs.expo.io/versions/latest/sdk/barometer/

Thanks for helping :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.