Hi I'm trying to use the community Capacitor Plugin within Ionic 5:-
https://github.com/CodetrixStudio/CapacitorGoogleAuth
My html looks like
</head>
<ion-header>
<ion-toolbar color="secondary">
<ion-title>
Capacitor testy
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<img [src]="image" *ngIf="image">
<ion-button (click)="openBrowser()">Open Browser</ion-button>
<ion-button (click)="takePicture()">Take Picture</ion-button>
<ion-button (click)="glogin()">glogin</ion-button>
</ion-content>
and my TS
import { Component } from '#angular/core';
import { Plugins, CameraResultType } from '#capacitor/core';
import { DomSanitizer } from '#angular/platform-browser';
const { Browser, Camera } = Plugins;
import '#codetrix-studio/capacitor-google-auth';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
image = null;
constructor(private sanitizer: DomSanitizer) {}
async openBrowser(){
await Browser.open({ url: 'https://www.neilson.co.uk/beach/greece/cosmos-beachclub' });
}
async takePicture() {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});
console.log('image: ', image)
this.image = this.sanitizer.bypassSecurityTrustResourceUrl(image && image.webPath);
}
async glogin(){
let auth = await Plugins.GoogleAuth.signIn();
console.log('auth' + auth);
}
}
But GoogleAuth.signIn(); gets a red underline in VS code - what is meant to get passed in here?
Thanks
In Android studio, locate file android/app/src/main/java///MainActivity.java, and add the plugin to the initialization list:
import com.codetrixstudio.capacitor.GoogleAuth.GoogleAuth
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
...
add(GoogleAuth.class);
...
}});
source: https://enappd.com/blog/google-login-in-ionic-react-capacitor-apps/122/
Related
I am implementing push notification in my Ionic 6 App. I am using #capacitor/push-notifications plugin to manage push notification in my Ionic App.
import { Injectable } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import { PushNotifications } from '#capacitor/push-notifications';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root',
})
export class FcmService {
constructor(private router: Router) {}
initPush() {
const fcmtoken = localStorage.getItem('fcmtoken');
if (Capacitor.platform !== 'web' && !fcmtoken) {
this.registerNotifications();
}
}
registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}
await PushNotifications.register();
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
localStorage.setItem('fcmtoken', token.value);
});
await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});
await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});
await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
alert(JSON.stringify(notification));
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}
getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
}
}
I am calling the initPush() from AppComponent and i am receiving notification in my app. But when i tap on that notification nothing happens. pushNotificationActionPerformed event is not getting triggered. Am i missing some configuration. I am using it in Android app.
Please help if someone has implemented it.
This code for finduserdetail by hitting function with help of dispatch method and passing (match.params.id) not working, even function not called as I know on dispatch method it should be called how may I call this so that our stat could be update in root.js file then I can show detail on my ui by using useselector
in productDetail.js
import { Fragment } from "react";
import Carousel from "react-material-ui-carousel";
import {useParams} from "react-router-dom";
import './ProductDetails.css';
import {useDispatch} from "react-redux";
import { useEffect } from "react";
import { getProductDetail } from "../../actions/productAction";
const ProductDetails = () =>{
console.log("hello this is detail")
const dispatch= useDispatch();
let params = useParams()
const id= params.id;
// const {product,error} = useSelector(
// (state) =>state.product)
useEffect(()=>{
dispatch(getProductDetail(id))
}, [dispatch, id])
return(
<Fragment>
<div className="ProductDetails">
<div>
<Carousel>
{/* {product.images &&
product.images.map((item,i)=>{
<img
className="CarouselImage"
key={item.url}
src={item.url}
alt={`${i} Slide`}
/>
})} */}
</Carousel>
</div>
</div>
</Fragment>
);
};
export default ProductDetails
and using for calling api for findproductDetail using getProductDetail in productAction.js
export const getProductDetail =(id) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_DETAILES_REQUEST });
const { data } = await axios.get(`/api/v1/product/${id}`);
dispatch({
type: PRODUCT_DETAILES_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: PRODUCT_DETAILES_FAIL,
payload: error.response.data.message,
});
}
};
and one other file productReducer.js
export const productDetailsReducer = (state = { product: {} }, action) => {
switch (action.type) {
case PRODUCT_DETAILES_REQUEST:
return {
loading: true,
...state,
};
case PRODUCT_DETAILES_SUCCESS:
return {
loading: false,
product: action.payload.product,
};
case PRODUCT_DETAILES_FAIL:
return {
loading: false,
error: action.payload,
};
and another file store.js
import { legacy_createStore as createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { productDetailsReducer, productReducer } from './reducers/productReducer';
const reducer = combineReducers({
products: productReducer,
product: productDetailsReducer,
});
let initialState ={};
const middleware = [thunk];
const store = createStore(reducer, initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
These stuff not working. I am quite beginner in React programming
import { Fragment } from "react";
import Carousel from "react-material-ui-carousel";
import {useParams} from "react-router-dom";
import './ProductDetails.css';
import {useDispatch} from "react-redux";
import { useEffect } from "react";
import { getProductDetail } from "../../actions/productAction";
const ProductDetails = () =>{
console.log("hello this is detail")
const dispatch= useDispatch();
let params = useParams()
const id= params.id;
// const {product,error} = useSelector(
// (state) =>state.product)
useEffect(()=>{
dispatch(getProductDetail(id))
}, [dispatch, id])
return(
<Fragment>
<div className="ProductDetails">
<div>
<Carousel>
{/* {product.images &&
product.images.map((item,i)=>{
<img
className="CarouselImage"
key={item.url}
src={item.url}
alt={`${i} Slide`}
/>
})} */}
</Carousel>
</div>
</div>
</Fragment>
);
};
export default ProductDetails
and using for calling api for findproductDetail using getProductDetail in productAction.js
export const getProductDetail =(id) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_DETAILES_REQUEST });
const { data } = await axios.get(`/api/v1/product/${id}`);
dispatch({
type: PRODUCT_DETAILES_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: PRODUCT_DETAILES_FAIL,
payload: error.response.data.message,
});
}
};
and one other file productReducer.js
export const productDetailsReducer = (state = { product: {} }, action) => {
switch (action.type) {
case PRODUCT_DETAILES_REQUEST:
return {
loading: true,
...state,
};
case PRODUCT_DETAILES_SUCCESS:
return {
loading: false,
product: action.payload.product,
};
case PRODUCT_DETAILES_FAIL:
return {
loading: false,
error: action.payload,
};
and another file store.js
import { legacy_createStore as createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { productDetailsReducer, productReducer } from './reducers/productReducer';
const reducer = combineReducers({
products: productReducer,
product: productDetailsReducer,
});
let initialState ={};
const middleware = [thunk];
const store = createStore(reducer, initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
The most important stuff my redux state is not updating because of id matching condition once if
state will get update I am checking using redux tool
How to dismiss my simple Ionic 4 loader (spinner), when the data is ready?
There must be a simple way to do that, but somehow I cannot find a good example.
Spinner:
async runSpinner(loadingId: string) {
const loading = await this.loadingController.create({
id: loadingId,
message: 'Loading...'
});
await loading.present();
const { role, data } = await loading.onDidDismiss();
}
Data (when this is loaded, spinner should stop)
this.someService
.getCustomizationResult(requestData)
.subscribe(data => {
// if (data) {
// ...
});
I've tried to do it with setting a boolean, but it didn't work. Thanks in advance!
You could go for this approach:
use a boolean value to show/hide a loading spinner
set the spinner as active when you enter the page with ionViewWillEnter
when your data loads, set the spinner to false
don't forget to hide the spinner when your service sends an error, otherwise the spinner won't hide to show an error msg for example.
Example
<ion-content>
<ion-grid>
<ion-row *ngIf="spinner">
<ion-col size="12">
// You can customize this the way you want
<ion-spinner></ion-spinner>
</ion-col>
</ion-row>
<ion-row *ngIf="!spinner">
// When the data loads, show this ...
</ion-row>
</ion-grid>
</ion-content>
spinner: boolean;
ionViewWillEnter() {
this.spinner = true;
}
getCustomizationResult() {
this.someService
.getCustomizationResult()
.subscribe({
next: (data) => {
// data
this.spinner = false;
},
error: (error) => {
// error
this.spinner = false;
}
});
}
Check this one
const loading = await this.loadingController.create({
message: 'Loading...'
});
}
// start working
loading.present().then( async ()=> {
/////Call your services to get data
}).then( async() => {
loading.dissmiss();
});
I am making a simple crud with Ionic4, everything is working fine. When i update my record via put call and navigate back to detail of the record to see updated values it shows old values. My update and navigate code is:
async updateClient() {
await this.api.updateClient(this.route.snapshot.paramMap.get('id'), this.clientForm.value)
.subscribe(res => {
let id = res['_id'];
this.router.navigate(['/client/detail', id]);
}, (err) => {
console.log(err);
});
}
And detail page code is:
import { Component, OnInit } from '#angular/core';
import { LoadingController } from '#ionic/angular';
import { RestApiService } from '../../rest-api.service';
import { ActivatedRoute, Router } from '#angular/router';
import {Location} from '#angular/common';
#Component({
selector: 'app-detail',
templateUrl: './detail.page.html',
styleUrls: ['./detail.page.scss'],
})
export class DetailPage implements OnInit {
client: any = {};
constructor(public api: RestApiService,
public loadingController: LoadingController,
public route: ActivatedRoute,
public router: Router,
private location: Location) {}
async getClient() {
console.log('in getClient');
const loading = await this.loadingController.create({
});
await loading.present();
await this.api.getClientById(this.route.snapshot.paramMap.get('id'))
.subscribe(res => {
console.log(res);
this.client = res;
loading.dismiss();
}, err => {
console.log(err);
loading.dismiss();
});
}
ngOnInit() {
this.getClient();
}
Try to call this.getClient() method in ionViewWillEnter() method as below :
ionViewWillEnter(){
this.getClient();
}
It will call your this.getClient() method every time when you enter in the page whether it is loaded or not.
I am fetched data from api but the problem is
when i am show data in render method then it showing "Undefine"
Please Help me to fix it
This is my code:-
var ProductData=''
export default class ApiProduct extends Component {
FetchProduct=()=>{
fetch('https://drawtopic.in/projects/wordpress/wp- json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b',{
method:'GET',
})
.then((response) => response.json())
.then((res) =>{
ProductData= res;
})
}
render() {
{this.FetchProduct()}
{console.warn(ProductData)}
return (
<View/>
)}
i Want to Show All data in render method
Here is a quick Expo example that should show you how to render a simple list. It is not a good idea to call fetch inside the render method, as every re-render will call the fetch.
Here is an expo snack https://snack.expo.io/S1-LKIyQE
import React from 'react';
import { Text, View, StyleSheet, FlatList, SafeAreaView } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
productData: []
}
}
async componentDidMount () {
await this.getData();
}
async getData() {
try {
let url ='https://drawtopic.in/projects/wordpress/wp-json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b'
let response = await fetch(url, { method:'GET' });
let responseJson = await response.json();
this.setState({productData: responseJson});
} catch (err) {
console.warn(err);
}
}
renderItem = ({item}) => {
return (
<View style={styles.mainItem}>
<Text>{item.name}</Text>
</View>
);
}
keyExtractor = (item, index) => {
return index.toString();
}
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
extraData={this.state}
data={this.state.productData}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white'
},
mainItem: {
width:200,
height: 80,
justifyContent: 'center',
alignItems: 'center',
margin: 10,
backgroundColor: 'yellow',
borderColor: 'black',
borderWidth: 1
},
});
Here I have used async/await as it can make for much cleaner and clearer code. This is a great article on the differences between promises and async/await https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8.
I have also given you a quick example on how to use a FlatList to display your data. You should check the docs on how to use it properly https://facebook.github.io/react-native/docs/flatlist
If you want to edit how each item is displayed on the screen then you need to update the renderItem method.
Try this way, if you have a question of how it works makes me to know.
let self;
export default class ApiProduct extends Component {
constructor(){
super();
self = this;
this.state = {
productData: null;
};
}
FetchProduct=()=>{
fetch('https://drawtopic.in/projects/wordpress/wp- json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b',{
method:'GET',
})
.then((response) => response.json())
.then((res) =>{
self.setState({ productData: res});
});
}
render() {
this.FetchProduct();
console.warn(self.state.productData);
return (
<View/>
);
}
I'll try to make order in your code.
Fetching data in the render method is not a good idea, it's better to use lifecycle methods, like componentDidMount. In order to handle your request result, set a state field and in your render read data from that field. So:
export default class ApiProduct extends Component {
constructor(){
super();
this.state = {
productData: undefined;
};
}
async componentDidMount(){
await this.fetchProduct();
}
fetchProduct = () => {
fetch('https://drawtopic.in/projects/wordpress/wp- json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b',{
method:'GET',
})
.then((response) => response.json())
.then((res) =>{
this.setState({
productData: res
})
})
}
render() {
const {productData} = this.state;
console.log(productData);
return (
<View/> // add here your code to render data properly
)
}}