(Disclaimer - I am a noob) I have come across an issue while trying to implement Capacitors Device API into my Ionic React project. The props (mobileInfo) being passed to my DeviceView function are undefined. Can anybody possibly explain why that is?
DeviceContainer.tsx*
import {Component} from "react";
import DeviceView from './DeviceView';
import React, { useEffect, useState } from 'react';
import { Device } from '@capacitor/device';
export class DeviceContainer extends React.Component {
state: { mobileInfo: string }
constructor(props: any) {
super(props)
this.state =
{
mobileInfo: "",
}
}
async getDeviceInfo (){
const info = Device.getInfo();
this.setState({
mobileInfo: JSON.stringify(info)
});
}
componentDidMount() {
this.getDeviceInfo();
}
render() {
return (
<DeviceView
mobileInfo={this.state.mobileInfo}
/>
)
}
}
export default DeviceContainer;
DeviceView.tsx*
import React from 'react'
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import DeviceContainer from './DeviceContainer'
import { RouteComponentProps } from 'react-router';
const DeviceView = ({ mobileInfo }: any) => {
if (mobileInfo !== undefined) {
console.log('prop was passed');
} else {
console.log('prop was NOT passed');
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Device Info</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<div>
<div>
Mobile Info: {mobileInfo}
</div>
</div>
</IonContent>
</IonPage>
)
}
export default DeviceView;
I am expecting the DeviceView.tsx to display the users device info using the mobileInfo prop.
CodePudding user response:
Try to await
Device.getInfo()
, because this method is async.
async getDeviceInfo(){
const info = await Device.getInfo();
console.log('---info', info)
this.setState({
mobileInfo: JSON.stringify(info)
});
}
async componentDidMount() {
await this.getDeviceInfo();
}