firestore update function is not working properly - android

in my react native app im trying to get user position when app opened only once
heres my code below.
async function GetUserDoc() {
let userData = await userDataRef.get().catch(error => Alert.alert("getuser" + error.message))
const uid = userData.docs.map(x => x.id)
if (uid.length > 0) {
PosRefresher(uid[0])
}
}
async function PosRefresher(uid) {
if (uid.length > 0) {
let loc = await Location.getCurrentPositionAsync();
const ref = firestore().collection('users').doc(uid)
ref.get().then(doc => {
if (doc.exists) {
if (loc.coords.latitude !== 0 && loc.coords.longitude !== 0) {
console.log("posupdate")
ref.update({
lastKnownPosition: new firestore.GeoPoint(loc.coords.latitude, loc.coords.longitude)
})
}
}
}).catch(err => console.log("setposupdate err", err))
}
}
when i check console log i can see "posupdate" so its seems like working. but when i check firestore user location not updates.
if im refresh app from metro its updating
but if i close app totally and reopen its not updating. what am i missing?
thanks

Related

React PWA detect new content on iOS is not working as expected

I use CRA PWA and add toast that's show when onupdatefound and onstatechange. it's working well in android and pc but in iOS it's not shown and content not refresh till close tab and open it again.
I searching long time and not found any good answer for this issue.
I have ServiceWorkerWrapper.ts
import React, { FC, useEffect } from 'react';
import { Snackbar, Button } from '#material-ui/core';
import * as serviceWorker from '../serviceWorkerRegistration';
const ServiceWorkerWrapper: FC = () => {
const [showReload, setShowReload] = React.useState(false);
const [counter, setCounter] = React.useState(0);
React.useEffect(() => {
let timer:any;
if (counter >= 0 && showReload) {
setTimeout(() => setCounter(counter - 1), 1000)
} else if (showReload) {
reloadPage();
}
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [counter]);
const onSWUpdate = (registration: ServiceWorkerRegistration) => {
if (registration && registration.waiting) {
setShowReload(true);
setCounter(2)
} else {
setShowReload(false);
}
};
useEffect(() => {
serviceWorker.register({ onUpdate: onSWUpdate });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const reloadPage = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistration()
.then((reg:any) => {
reg.waiting.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
})
.catch((err) => console.log('Could not get registration: ', err));
}
};
return (
<Snackbar
open={showReload}
message="A new version is available!"
onClick={reloadPage}
ContentProps={{
className: "reload-snackbar"
}}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
action={
<Button
color="inherit"
size="small"
onClick={reloadPage}
>
Reload{showReload ? ` (${counter + 1})`:''}
</Button>
}
/>
);
}
export default ServiceWorkerWrapper;
serviceWorkerRegistration.ts
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
if (navigator.vendor === 'Apple Computer, Inc.') {
console.log('Safari!!!!');
if (registration.waiting) {
if (config && config.onUpdate) {
config.onUpdate(registration);
}
}
}
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
service-worker.ts
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.

Unable to send push notification to android device using firebase cloud messaging

I am trying to send a notification to an android device using firebase cloud messaging.
Below is sendNotification which is a cloud function I have deployed on firebase:
const sendNotification = (owner_uid: any, type: any) => {
return new Promise((resolve, reject) => {
admin.firestore().collection('users').doc(owner_uid).get().then((doc) => {
if (doc.exists && doc.data()?.token) {
if (type === 'new_comment') {
console.log('NEW COMMENT');
console.log('TOKEN: ' + doc.data()?.token);
admin.messaging().sendToDevice(doc.data()?.token, {
data: {
title: 'A new comment has been made on your post',
}
}).then((sent) => {
console.log("SENT COUNT " + sent.successCount);
console.log('SENT APPARENTLY')
resolve(sent);
});
}
}
});
});
}
And here is where I'm calling this function:
export const updateCommentsCount = functions.firestore.document('comments/{commentId}').onCreate(async (event) => {
const data = event.data();
const postId = data?.post;
const doc = await admin.firestore().collection('posts').doc(postId).get();
if (doc.exists) {
let commentsCount = doc.data()?.commentsCount || 0;
commentsCount++;
await admin.firestore().collection('posts').doc(postId).update({
'commentsCount': commentsCount
})
return sendNotification(doc.data()?.owner, 'new_comment');
} else {
return false;
}
})
However, I'm not receiving a notification on the android device.
And here are the cloud function logs when I leave a comment:
Can someone please tell me why is happening, & how it can be resolved? I can show further code if required.
I managed to find the solution.
In the notification sending method, sendToDevice, I updated the key "data", to "notification" and the notification is now being automatically sent & displayed on the original user's device.
Here is the updated
admin.messaging().sendToDevice(doc.data()?.token, {
notification: {
title: 'A new comment has been made on your post',
}

tipsi-stripe 3d secure at react-native

I want to integrate Stripe 3d secure in my react native app. Using this lib: https://github.com/tipsi/tipsi-stripe, and with simple payment it works well. But with 3D I have several problem on iOS and also on Android:
iOS: createCardSource: true (at line 7 crashing the app).(Solved)
iOS: Stucked before redirection on the secure page
Android: How I know if the user paid or decline the payment at the remote page?(At line 27 no any data in the secure3dSourceResponse object)
import stripe from "tipsi-stripe";
paymentRequest = async (mutation, deal) => {
let paymentRequest;
try {
paymentRequest = await stripe.paymentRequestWithCardForm({
...options,
createCardSource: true
});
//iOS and Android gets back different objects.
const threeDSecure = Platform.OS === "android"
? paymentRequest.card.three_d_secure
: paymentRequest.details.three_d_secure;
if (
threeDSecure === "recommended"
|| threeDSecure === "required"
) {
let prefix = Platform.OS === "android"
? `appName://appName/`
: `appName://`;
let secure3dSourceResponse = null;
try {
const { dealFeeUSD } = this.state;
// On iOS the process stucked here, without any error message
secure3dSourceResponse = await stripe.createSourceWithParams({
type: "threeDSecure",
amount: dealFeeUSD || 3000,
currency: "USD",
flow: "redirect",
returnURL: prefix,
card: paymentRequest.sourceId
});
// On android I have no any data in secure3dSourceResponse after Stripe returns from their page.
} catch (error) {
console.log('secure3dSourceResponse', secure3dSourceResponse)
}
} else {
if (paymentRequest && paymentRequest.tokenId) {
this.handlePayDeal(mutation, deal, paymentRequest.tokenId);
}
}
} catch (error) {
console.log("paymentRequest: " + JSON.stringify(error));
}
};

React Native AsyncStorage stops working once app is offline

I have a relatively simple app (my first) that needs to display information that is retrieved from a GraphQL query and then stored in AsyncStorage. Everything works fine until you turnoff data/Wifi connections and relaunch the app - it will not load the same local data it did when networking is on. This is the same on a physical or emulated Android device.
There are no data calls except when the user initially sets their details. The app is built with version 2.7.1 of Expo & AWS Amplify. I have wasted several days with this final issue and gotten the same behaviour with Expo SecureStore & Amplify Cache and am loath to go down the route of learning and including Redux on such a simple app...
//import from react native not react
import { AsyncStorage } from 'react-native'
//calling a function as app loads
componentDidMount() {
this._loadInitialState();
}
//retrieving String from AsyncStorage
_loadInitialState = async () => {
try {
const policyNum = await AsyncStorage.getItem('policyNum')
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.state.policyNumSet = true
try {
await AsyncStorage.setItem('policyNum', policyNumber)
} catch (err) {
//...
}
}
}
You are using badly the fact of change the state.
Where you do this:
this.state.policyNumSet = true
You should change the state with the setState() function like this:
this.setState({ policyNumSet: true })
This was a conflict with an external API
Are you storing a string? asyncstorage only can store strings . try using JSON.stringify and JSON.parse
_loadInitialState = async () => {
try {
var policyNum = await AsyncStorage.getItem('policyNum')
policyNum = JSON.parse(policyNum) // converting to original
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.setState({ policyNumSet: true })
try {
var policyNumberString = JSON.stringify(policyNumber)
await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
} catch (err) {
//...
}
}
}

How to know when the AsyncStorage in React-Native is Full?

I want to know when AsyncStorage is full in react native.
What do Error value we get when the AsyncStorage is full to react native or will something else happen?
We can get a value from AsyncStorage using the below code
try {
const value = await AsyncStorage.getItem('TASKS');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
if someone can suggest me a check in the above code to know when AsyncStorage is full. It would be really helpful.
Do the steps
import {AsyncStorage} from 'react-native';
AsyncStorage.setItem('Islogin', 'Yes');
And check that you have stored or not.
_storeData = async () => {
try {
let value = await AsyncStorage.getItem('Islogin');
if (value) {
if (value == 'Yes'){
console.log("You are auto login");
}else{
console.log("abc");
}
}else{
console.log("abc");
}
} catch (error) {
console.log("error" + error);
}
}

Categories

Resources