Home > Back-end >  How to run a function constantly when focused on a react native navigation page
How to run a function constantly when focused on a react native navigation page

Time:07-24

I am using react native sensors to detect gyroscope and accelerometer data about my phone, but I want to use both of these values together in unison for my app. I want the gyroscope value to be multiplied by the accelerometer data, and for this I need a continuous loop that runs about every 20ms. I want the function to only run when the page is open, to avoid lag and I want to to be access all the variables normal js code would be able to access (accelerometer data and gyro data).

Here is the function I have written already, but failed:

const [updateFunction, setUpdateFunction] = useState(0);

    useEffect(() => {
      setUpdateFunction(setInterval(() => {
        console.log("Update")
      }), 20);

      return () => {
        clearInterval(updateFunction);
      }
    })

Here is my full code:

import { View, Text, TouchableOpacity, Alert } from 'react-native';

import AppStyles from '../styles/styles'

import { Gyroscope, Accelerometer } from 'expo-sensors';

import { useState, useEffect } from 'react';

import * as React from 'react';

function Home(props) {
    // Gyroscope Data

    const [gyroData, setGyroData] = useState({
      x: 0,
      y: 0,
      z: 0
    });

    // Accelerometer Data

    const [accelData, setAccelData] = useState({
      x: 0,
      y: 0,
      z: 0
    });

    const [accelSpeed, setAccelSpeed] = useState(0);

    // Device Orientation

    const [deviceOrientation, setDeviceOrientation] = useState({
      x: 0,
      y: 0,
      z: 0
    });

    // Gyro Data

    const [gyroSubscription, setGyroSubscription] = useState(null); // Gyroscope

    const [accelSubscription, setAccelSubscription] = useState(null); // Accelerometer

    Gyroscope.setUpdateInterval(1000);

    Accelerometer.setUpdateInterval(100);

    // Gyroscope

    const _gyrosubscribe = () => {
      setGyroSubscription(
        Gyroscope.addListener(gyroscopeData => {
          setGyroData(gyroscopeData);
        })
      );
    };
  
    const _gyrounsubscribe = () => {
      gyroSubscription && gyroSubscription.remove();
      setGyroSubscription(null);
    };

    const _accelsubscribe = () => {
      setAccelSubscription(
        Accelerometer.addListener(accelerometerData => {
          setAccelData(accelerometerData);
          setAccelSpeed(Math.floor(Math.abs(1 - Math.cbrt(Math.pow(accelerometerData.x, 2)   Math.pow(accelerometerData.y, 2)   Math.pow(accelerometerData.z, 2))) * 100));
        })
      );
    };

    const _accelunsubscribe = () => {
      accelSubscription && accelSubscription.remove();
      setAccelSubscription(null);
    };

    // Device Orientation Update Function

    const [updateFunction, setUpdateFunction] = useState(0);

    useEffect(() => {
      setUpdateFunction(setInterval(() => {
        console.log("Update")
      }), 20);

      return () => {
        clearInterval(updateFunction);
      }
    })

    // Page Navigation

    const navigation = props.navigation;

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around', marginTop: 50 }}>
          <Text style={AppStyles.homescreentitle}>Phone Soundboard</Text>
          <View style={{height: "70%", width: "100%", alignItems: "center"}}>
            <TouchableOpacity style={AppStyles.homebuttontouchableopacity} onPress={() => {
              navigation.navigate("mouse");
            }}>
                <Text style={AppStyles.homebuttontext}>
                  Mouse
                </Text>
            </TouchableOpacity>
            <TouchableOpacity style={AppStyles.homebuttontouchableopacity} onPress={() => {
              navigation.navigate("test");
            }}>
                <Text style={AppStyles.homebuttontext}>
                  Test Section
                </Text>
            </TouchableOpacity>
            <TouchableOpacity style={AppStyles.homebuttontouchableopacity} onPress={() => {
              
            }}>
                <Text style={AppStyles.homebuttontext}>
                  Check for Dev Update Func
                </Text>
            </TouchableOpacity>
            <View>
              <Text>
                Device Orientation Data: x: {deviceOrientation.x} y: {deviceOrientation.y} z: {deviceOrientation.z}
              </Text>
              <Text>
                Gyroscope Data: x: {gyroData.x} y: {gyroData.y} z: {gyroData.z}
              </Text>
              <Text>
                Accelerometer Data: {
                  accelSpeed
                }
              </Text>
            </View>
          </View>
        </View>
      );
}

export default Home;

CodePudding user response:

You don't need a seperate update function and loop thingy. Just put the code in a useEffect with the two vairables you're interested in, in the dependancy array.

E.g.:

const [multData, setMultData] = useState(0);

useEffect(() => {
    const multData = /* fancy stuff */
    setMultData(multData);
}, [accelData, gyroData]);

I've never used the sensor library, but it seems like you are already subscribing to their change, and they should update when they change.

  • Related