简体   繁体   中英

Ionic 5 React Capacitor / Cordova cordova-plugin-uid

I am new in Ionic and React. I am trying to build component what is tracking GPS coordinates of device and send them via AJAX to the backend API. I was able to develop the tracking including sending data to API but I dont know how to initiate and display / store device UID.

I did follow a guide here https://ionicframework.com/docs/native/unique-device-id but there is no info how to initiate plugin in React, always only in Angular.

Here is the code:

import React from "react";
import { stopwatchOutline, play, stop } from "ionicons/icons";
import {
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonContent,
  IonIcon,
  IonGrid,
  IonRow,
  IonCol,
  IonButton,
} from "@ionic/react";

import { UniqueDeviceID } from '@ionic-native/unique-device-id/ngx';

type State = {
  intervalID: number;
  latitude: number;
  longitude: number;
  trackingEnabled: boolean;
  counter: number;
  device_id: string;
};


class GPS extends React.Component<any, State> {
  constructor(props: any) {
    super(props);

    this.state = {
      intervalID: 0,
      latitude: 0,
      longitude: 0,
      trackingEnabled: false,
      counter: 0,
      device_id: '',
    };
  }

  startTracking = () => {
    this.setState({ trackingEnabled: true });

    const intervalID = window.setInterval(() => {
      navigator.geolocation.getCurrentPosition((position) => {
        let latitude = position.coords.latitude;
        let longitude = position.coords.longitude;

        if (latitude > 0 && longitude > 0) {
          if (
            latitude !== this.state.latitude &&
            longitude !== this.state.longitude
          ) {
            fetch("http://xyz", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                device_id: 123456,
                lat: latitude,
                lng: longitude,
              }),
            })
              .then(async (response) => {
                const data = await response.json();
                if (!response.ok) {
                  const error = (data && data.message) || response.status;
                  return Promise.reject(error);
                }

                console.log(data);
              })
              .catch((error) => {
                console.error("There was an error!", error);
              });
          } else {
            console.log(
              "lat: " + latitude + ", lng: " + longitude + " are without change"
            );
          }
        }

        this.setState({ latitude: latitude, longitude: longitude, counter: this.state.counter+1 });

        console.log("lat: " + latitude + ", lng: " + longitude, " counter: " + this.state.counter);

        if(this.state.counter > 10) {
          this.setState({ trackingEnabled: false });
          window.clearInterval(this.state.intervalID);
          console.log("stop after thousands call");
        }
      });
    }, 2000);

    this.setState({ intervalID: intervalID });

    console.log("start");
  };

  stopTracking = () => {
    this.setState({ trackingEnabled: false });
    window.clearInterval(this.state.intervalID);
    console.log("stop");
  };

  render() {
    return (
      <IonPage>
        <IonHeader>
          <IonToolbar color="primary">
            <IonTitle>
              <IonIcon icon={stopwatchOutline} /> &nbsp; GPS tracker
            </IonTitle>
          </IonToolbar>
        </IonHeader>
        <IonContent>
          <IonGrid>
            <IonRow>
              <IonCol>
                <h3>lat: {this.state.latitude}</h3>
                <h3>lng: {this.state.longitude}</h3>
                <h3>Device ID: {this.state.device_id}</h3>
              </IonCol>
            </IonRow>
            <IonRow>
              <IonCol>
                <IonButton
                  id="start_tracking"
                  color="primary"
                  expand="block"
                  strong={true}
                  size="large"
                  disabled={this.state.trackingEnabled}
                  onClick={this.startTracking}
                >
                  <IonIcon icon={play} /> Start
                </IonButton>
              </IonCol>
              <IonCol>
                <IonButton
                  id="stop_tracking"
                  color="light"
                  expand="block"
                  size="large"
                  disabled={!this.state.trackingEnabled}
                  onClick={this.stopTracking}
                >
                  <IonIcon icon={stop} /> Stop
                </IonButton>
              </IonCol>
            </IonRow>
          </IonGrid>
        </IonContent>
      </IonPage>
    );
  }
}

export default GPS;

In documentation is written this (for Angular):

import { UniqueDeviceID } from '@ionic-native/unique-device-id/ngx';

constructor(private uniqueDeviceID: UniqueDeviceID) { }

...

this.uniqueDeviceID.get()
  .then((uuid: any) => console.log(uuid))
  .catch((error: any) => console.log(error));

But I have no idea how to do it in React in my class. I spent 2 days with Googling and trying everything what I found but still no solution.

Thank you.

from the example here in documentation - https://ionicframework.com/docs/native/community#react

install

npm install @ionic-native/core
npm install cordova-plugin-uniquedeviceid
npm install @ionic-native/unique-device-id
ionic cap sync
import { UniqueDeviceID } from '@ionic-native/unique-device-id'

And then you just use it in your component

const uid = await UniqueDeviceID.get()

Ok, I did try it but does not work. Here is the error message:

SyntaxError: F:\hybrid-app-development\job\sportis\gps-tracking\src\pages\GPS.tsx: Unexpected token, expected ";" (40:22)
[react-scripts]   38 |     };
[react-scripts]   39 | 
[react-scripts] > 40 |     const uid = await UniqueDeviceID.get();
[react-scripts]      |                       ^
[react-scripts]   41 |   }
[react-scripts]   42 | 
[react-scripts]   43 |   startTracking = () => {

And here is list of dependecies (so plugins should be installed):

{
    "@capacitor/core": "2.4.5",
    "@ionic-native/android-permissions": "^5.30.0",
    "@ionic-native/core": "^5.30.0",
    "@ionic-native/location-accuracy": "^5.30.0",
    "@ionic-native/unique-device-id": "^5.30.0",
    "@ionic/react": "^5.0.7",
    "@ionic/react-router": "^5.0.7",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^8.0.3",
    "@types/jest": "^24.0.25",
    "@types/node": "^12.12.24",
    "@types/react": "^16.9.17",
    "@types/react-dom": "^16.9.4",
    "@types/react-router": "^5.1.4",
    "@types/react-router-dom": "^5.1.3",
    "cordova-plugin-android-permissions": "^1.1.2",
    "cordova-plugin-request-location-accuracy": "^2.3.0",
    "cordova-plugin-uniquedeviceid": "^1.3.2",
    "ionicons": "^5.0.0",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^3.4.4",
    "react-useinterval": "^1.0.2",
    "typescript": "3.8.3"
  }

and here is a updated constuctor what returns that error:

constructor(props: any) {
    super(props);

    this.state = {
      intervalID: 0,
      latitude: 0,
      longitude: 0,
      trackingEnabled: false,
      counter: 0,
      device_id: '',
    };

    const uid = await UniqueDeviceID.get();
  }

I tried to put:

const uid = await UniqueDeviceID.get();

To the "startTracking" method but same problem.

Any different suggestions?

Thank you very much!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM