I'm creating an app that tracks the current location of the user and sends the data to the server every 5 secs. I'm using expo and there's an API called TaskManager
that needs to initialize outside the scope. Is there an alternative way to update the state outside the "export default" without using redux?.
export default class App extends Component {
constructor(props){
super(props)
}
state = {
mapRegion: null,
hasLocationPermissions: false,
locationResult: null,
marker: {
latitude: 0,
longitude: 0
},
latitude: 0,
longitude: 0,
location: null,
errorMessage: null
}
componentWillMount() {
this.onLoad();
}
componentDidMount() {
//console.log(store.getState())
}
onLoad = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
locationResult: 'Permission to access location was denied',
});
} else {
this.setState({ hasLocationPermissions: true });
}
let isRegistered = await TaskManager.isTaskRegisteredAsync(LOCATION_TRACKER)
if (!isRegistered) console.log('yes its waiting status:'+ isRegistered);
await Location.startLocationUpdatesAsync(LOCATION_TRACKER, {
accuracy: Location.Accuracy.High,
timeInterval: 2500,
distanceInterval: 0,
})
}
}
TaskManager.defineTask(LOCATION_TRACKER, ({ data, error }) => {
if (error) {
console.log(error)
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
//Right here, I need to update my state something like,
this.setState({
//...
}); //but ofcourse this not gonna work
console.log(locations)
}
});
You have a couple ways for make this works. First you can declare an global scope variable that will be storing you current location.
location = null;
TaskManager.defineTask(LOCATION_TRACKER, ({ data, error }) => {
if (error) {
console.log(error)
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
location = locations;
//Right here, I need to update my state something like,
this.setState({
//...
}); //but ofcourse this not gonna work
console.log(locations)
}
});
Or and I think this is the best way is to set up an state container like redux.
You can see all the docs here https://react-redux.js.org/ then calling actions in the TaskManager you will be able to save current location and dispatching to all connected components what its your current location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With