Help! Can't use TaskManager output in my app

Hello all,
I would appreciate any guidance you might have regarding this topic, thank you in advance.

Here is my situation:
I have set up TaskManager to track the location of the device it is running on, which is working great. Where I am struggling is getting the data returned by TaskManager into my App component as state. Here is a simplified example of my issue:

class App extends Component {
  state = {}
  // 'this' does not exist within a static method.
  static updateState = (data) => this.setState(data)
  render = () => { return <div>...</div> }
}
‚Äč
TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  const { locations } = data // How can I get locations into state?
  App.updateState(locations) // Won't work as I can't use 'this' within a static method!
})

The actual file looks like this:

/* eslint-disable react/prop-types */
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import * as Location from 'expo-location'
import * as TaskManager from 'expo-task-manager'
import * as Permissions from 'expo-permissions'

const LOCATION_TASK_NAME = 'background-location-task'

export default class App extends React.Component {
  state = {
    latitude: 0,
    longitude: 0,
  }

  static updateState(latitude, longitude) {
    // updateState receives the data correctly, I just can't 
    // work out how to update the component state with values.
    console.log(latitude, longitude) 
    // this.setState({ latitude, longitude }) // Doesn't work
  }

  notStaticUpdateState(latitude, longitude) {
    // console.log(latitude, longitude) // won't work
  }

  async componentDidMount() {
    const { status } = await Permissions.askAsync(
      Permissions.LOCATION,
      Permissions.USER_FACING_NOTIFICATIONS,
    )

    if (status === 'granted') {
      await Location.startLocationUpdatesAsync(
        LOCATION_TASK_NAME,
        {
          accuracy: Location.Accuracy.Highest,
          distanceInterval: 1,
          timeInterval: 1000,
        },
      )
    }
  }

  render() {
    const { latitude, longitude } = this.state
    return (
      <View style={styles.container}>
        <Text>Lat: {latitude}</Text>
        <Text>Lng: {longitude}</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
  },
})

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    return
  }
  if (data) {
    const { latitude, longitude } = data.locations[0].coords
    App.updateState(latitude, longitude)
    // App.notStaticUpdateState(latitude, longitude) // won't work
  }
})

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