react-native-geocoding shows error not getting coordinates - react-native

I am using https://github.com/marlove/react-native-geocoding to get coordinates in react-native.
Sample code
`Geocoder.from("visakhapatnam,andhra pradesh,india")
.then(json => {
var location = json.results[0].geometry.location;
console.log("location",location)
})
.catch(error => console.warn("routeMap Err",error));`
I am getting error
{"code": 4, "message": "Error from the server while geocoding. The received datas are in the error's 'origin' field. Check it for more informations.", "origin": {"error_message": "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started", "results": [], "status": "REQUEST_DENIED"}}

To use the Geocoding API you must have an API key. The API key is a unique identifier that is used to authenticate requests associated with your project for usage and billing purposes.
To get an API key:
Visit the Google Cloud Platform Console.
Click the project drop-down and select or create the project for
which you want to add an API key.
Click the menu button and select APIs & Services > Credentials.
On the Credentials page, click Create credentials > API key. The API
key created dialog displays your newly created API key.
Click Close. The new API key is listed on the Credentials page under
API keys.
(Remember to restrict the API key before using it in production.)
OR You need try enable billing like an error message.
Go to the Payment Account Management page in the Google Cloud
Platform Console and log in.
Select the My Projects tab to display the list of projects and the
payment accounts associated with each project.
In the list of projects, locate the project for which you want to
re-enable payments, and then click the menu (more_vert) next to it.
Select Change payment and select the destination payment account you
want.

did you provide api key to geocoded like this
Geocoder.init('your api key'); // use a valid API key

I had this problem because my google cloud free trial plan ended. When I upgraded to Blaze plan the error stopped happening.

Try this:
import React, {useEffect} from 'react';
import Geocoder from 'react-native-geocoding';
import {keys} from '../env';
First ensure your billing info and geocoding API are properly setup
and enabled.Then set up code to grant permission to avert future
issues
const _getCurrentPosition = async () => {
Geocoder.init(keys.GOOGLE_MAP_APIKEY); // initialized with a valid API key
const status = await locationPermission(); // write the function
if (status === 'granted') {
const location = await getCurrentLocation(); // write the function
console.log('Location Permission granted!');
console.log({currentLoc: location});
Geocoder.from({
latitude: location.latitude,
longitude: location.longitude,
})
.then(addressJson => {
const _location = addressJson.results[0].formatted_address;
console.log('location_', _location);
})
.catch(error => console.warn(error));
//or for non-geometry positions (plain addresses)
//**IMPORTANT** make sure the address is valid to avoid errors
//one way to do this is to first google a valid address
Geocoder.from("visakhapatnam")
.then(addressJson => {
const _location = addressJson.results[0].geometry.location;
console.log('location_', _location);
})
.catch(error => console.warn(error));
} else {
console.log('Permission not grantedd!');
}
};
useEffect(() => {
_getCurrentPosition();
}, []);
Don't forget to ALWAYS consult the documentation: https://www.npmjs.com/package/react-native-geocoding

Related

404 error calling GET API from a shopify theme-extension

I'm new to shopify development, and can't figure out how to call an authenticated API from a shopify theme-extension. Essentially, I'm trying to make a theme extension, where one of the functionalities is that when a checkbox is clicked, an API that counts the number of products is called.
I have a working api that gets the product count, and in web>index.js, I have set-up the end-point:
app.get("/api/products/count", async (_req, res) => {
const countData = await shopify.api.rest.Product.count({
session: res.locals.shopify.session,
});
res.status(200).send(countData);
});
Under web>frontend>hooks, I have the authenticated hooks set-up as shown below. I've tested that if I call the "api/products/count" API from one of the web pages using useAppQuery, it works as expected, and returns the product count.
import { useAuthenticatedFetch } from "./useAuthenticatedFetch";
import { useMemo } from "react";
import { useQuery } from "react-query";
export const useAppQuery = ({ url, fetchInit = {}, reactQueryOptions }) => {
const authenticatedFetch = useAuthenticatedFetch();
const fetch = useMemo(() => {
return async () => {
const response = await authenticatedFetch(url, fetchInit);
return response.json();
};
}, [url, JSON.stringify(fetchInit)]);
return useQuery(url, fetch, {
...reactQueryOptions,
refetchOnWindowFocus: false,
});
};
In my theme extension code, I've added an event listener to the checkbox which calls getProductCount. In getProductCount, I want to call /api/products/count:
import { useAppQuery } from "../../../web/frontend/hooks";
export const getProductCount = (product) => {
const {
data,
refetch: refetchProductCount,
isLoading: isLoadingCount,
isRefetching: isRefetchingCount,
} = useAppQuery({
url: "/api/products/count",
reactQueryOptions: {
onSuccess: () => {
setIsLoading(false);
},
},
});
}
However, when I run locally and click the checkbox, it returns a 404 error trying to find useAppQuery. The request URL is https://cdn.shopify.com/web/frontend/hooks. It seems like the authentication isn't working because that URL looks incorrect.
Am I missing a step that I need to do in order to call an authenticated API from a theme-extension?
I thought the issue was just the import path for useAppQuery but I've tried different paths, and they all return the same 404 issue.
If you want a hot tip here. In your theme App extension, you do not actually need to make an API call to get a product count. In your theme app extension, you can just use Liquid, and dump the product count out to a variable of your choice, and use the count, display the count, do whatever.
{{ shop.product_count }}
Of course, this does not help you if you need other storefront API calls in your theme App extension, but whatever. In my experience, I render the API Access Token I need in my theme app extension, and then making my Storefront API calls is just a fetch().
The only time I would use authenticated fetch, is when I am doing embedded App API calls, but that is a different beast from a theme app extension. In there, you do not get to make authenticated calls as the front-end is verboten for those of course. Instead you'd use App Proxy for security.
TL:DR; Storefront API calls with a token should not fail with a 404 if you call the right endpoint. You can use Storefront API inside a theme app extension. Inside a theme app extension, if you need backend Admin API access, you can use App Proxy calls.

Stripe Connect Account - return_url - Link back to Expo application

I'm on-boarding users onto Stripe connect. My node server generates a temporary HTTPS URL so that customers can sign on. According to their docs I need to provide a URL for when they complete the application.
https://stripe.com/docs/api/account_links/create#create_account_link
I have an Expo application. The user will open up the URL in their browser. However when they complete their application I would like them to go back to Expo App. If I try to use expo://MYAPP/ as the return_url, Stripe does not recognize the URL schema.
Does anyone have an idea how i can return the user back into my application after completing their on-boarding done via the browser?
For anyone one out there who runs into this post, this is was my solution. Your app has to link to a website. I am using Expo, but this is the React code to generate the link.
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
const openPage = async () => {
try {
const result = await WebBrowser.openAuthSessionAsync(
`${url}?linkingUri=${Linking.createURL('/?')}`,
);
let redirectData;
if (result.url) {
redirectData = Linking.parse(result.url);
}
setstate({ result, redirectData });
} catch (error) {
console.log(error);
}
};
When you load the site, make sure to pass the URL that was generated from your backend
Backend code:
stripe.accountLinks
.create({
type: 'account_onboarding',
account: accountID,
refresh_url: `https://website.com/refresh`,
return_url: `https://website.com/return`,
})
When the user has the site open, have a button that redirects to the stripe URL.This is how i thought it went first
App -> Stripe connect
instead you have to approach it like this
App -> Website -> Stripe connect

How to search users in Cognito userpool in React Native app

I'm building an app using React Native and Amplify (including authentication) and need to let users search for and follow other users also using the app.
The authentication flow is working fine, but I'm not able to search the cognito userpool for the list of users.
According to amplify-js/packages/amazon-cognito-identity-js/, one of the v1.0 functionality enabled "Search users in your pool using user attributes.", but so far I'm unable to find any additional documentation or examples.
I've tried using the Auth object from the aws-amplify module and the CognitoUserPool object from the amazon-cognito-identity-js module, and neither seems to offer the search functionality.
How should I be going about this?
Ended up with this:
AWS.config.update({
accessKeyId: "YOUR_ACCESS_KEY",
secretAccessKey: "YOUR_SECRET_ACCESS_KEY,
region: "YOUR_REGION"
});
const params = {
UserPoolId: 'THE_USER_POOL_ID',
AttributesToGet: [
'email',
],
};
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.listUsers(params, (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("data", data);
}
})
The problem now becomes having to store the access keys on-device, which I can't do. Will likely create another table in Datastore to store user info for querying.

React-native Geolocation. Wait for user's response to request

iOS issue only:
I am using the following code to get the users location.
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Native GEO GOOD", position);
return resolve(position)
},
(err) => {
console.log("Native GEO BADD", err);
return reject(err)
},
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 0 },
)
The above code opens a dialog box, from which the user can allow my app to geolocate.
The problem is I want to wait until the user actually responds using the dialog box before calling the error or success callback.
I tried to use: requestAuthorization(). But that just opens the dialog box and I have no way to telling when the user has accepted the request to geolocate.
What I would like to do is ask the users permission to geolocate, then after the user accepts, try to geolocate the user.
But I don't see how to do that using react-native geolocation.
If requestAuthorization() took a callback option for when the user responds to the dialog box, that would solve my issue.
In React-Native using Expo (https://expo.io) you ask for permissions using a Promise and then act on the promise (hopefully when permission is given).
Permissions.askAsync((Permissions.LOCATION)
.then(({status}) => {
//your code here after permission is granted
});
);
If you aren't using expo, there is a Component call react-native-permissions (https://github.com/yonahforst/react-native-permissions.git) that allows you to request permissions using a promise like my example but without expo. Their example shows the request setting state to let you know the permissions status which you can act on.
Permissions.request('location', { type: 'always' }).then(response => {
this.setState({ locationPermission: response })
})

How to change the status of the user using react-native-facebook-login

I installed react-native-google-signin. The function GoogleSignin.currentUserAsync() detects a change of the user's status when it is registered.
const user = GoogleSignin.currentUserAsync();
this.setState({user});
When I use react-native-facebook-login, how should I change the status of the user?
Basically there are two ways of using the package, one is to import the FBLogin button, the other is to create your own button and call the FBLoginManager. I am not 100% certain what do you mean by change the status of the user, but if you just want to set the state after user signs in, the idea is like this, very similar to your google code
FBLoginManager.loginWithPermissions(["email","user_friends"],(err, data) => {
if (!err) {
this.setState({user: data});
this.props.onLogin(data.credentials); // whatever your logic is
}
});
Here I am using the FBLoginManager, if you need a FBLogin example their document would be a perfect place to refer
https://github.com/magus/react-native-facebook-login
To streamline your code, you could use a framework like Invertase's React Native Firebase, which can handle Google, Facebook, and Twitter auth changes with the same API. Using this, you can just do the following:
componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in.
} else {
// User has signed out
}
});
}