how to catch error in firestore when no internet - javascript

I recently updated my app from firebase to firestore but stuck at offline persistance. I am using react-native-firebase to integrate firestore and disable its perisistance but still not getting any catch error when no internet.
This is my code to delete data but catch never gets error when no internet not is the promise resolved.
firebase.firestore().collection('d').doc(deviceid).delete().then(function () {
console.log("Device Deleted");
that.setState({
loading: false
});
Toast.show('Device Deleted Succesfully', {
duration: Toast.durations.SHORT,
position: Toast.positions.TOP,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});
}).catch(function (err) {
console.log(err);
that.setState({
loading: false
});
})

Firestore and Realtime Database SDKs don't throw errors when there is no network connectivity. They will silently retry the connection in hopes that the device will regain network connectivity soon. The reason for this is because most developers don't want their apps to appear broken just because the user went into a tunnel and back out, or switched between mobile towers in a way that forced a network reset.
In order to effectively make use of an online database, the device should be online most of the time, and this the situation that the SDK is optimizing for.

Make your own helper function for deletion that throws an error if there is no Internet connection. You can make the API cleaner by not calling .collection() but rather passing the full path d + deviceid to it.
function onlineOnlyDelete(path) {
if(!deviceApi.hasInternet()) throw 'No Internet, no delete'
return firebase.firestore().doc(path).delete()
}
replace firebase.firestore().collection('d').doc(deviceid) with onlineOnlyDelete(d+deviceid) and you should be good to go

Referencing this thread. I set up the following check:
.then(() => {
if (snapshot.empty && snapshot.metadata.fromCache) {
throw new Error('Failed to fetch ideas');
}
})
Then later on I caught the error and set the app state to include the error along with parameters specific to the batch like startIndex and stopIndex which will be important later. When rendering the documents, one case is reserved for the BatchError as I dubbed it, in which case the user is going to see a Refetch button which has a callback attached to it. Using the batch metadata, the callback is able to reinitialize the specific batch request.

Related

Want client-side Firebase logs to show up in StackDriver, not users' browsers

I'm using firebase-functions/lib/logger to log client-side firebase/firestore activity like
const { log, error } = require("firebase-functions/lib/logger");
export const addData = async (userId, dataId) => {
try {
const collectionRef = firestore
.collection("docs")
await collectionRef.add({
dataId,
});
log(`Data added`, { userId, dataId });
} catch (err) {
error(`Unable to add new data`, { userId, dataId });
throw new Error(err);
}
};
When I run this on my local, the log shows up in my browser console. Will this happen on non-local environments, ie for real users? Will these logs also show up automatically in Stackdriver, or are they stuck on the client side? I want to be able to view the logs either in Stackdriver or Firebase console but have them not show up in the browser for real users. How should I accomplish this?
Messages logged in Cloud Functions will not show up in the client app at all (that would probably be a security hole for your app). They will show up in the Cloud Functions console in the log tab, and in StackDriver.
Any messages logged in your app will not show up in any Google Cloud product. They are constrained to the device that generated them. If you want cloud logging, you'll need to implement some other solution. Cloud Functions does not support this - you will need to investigate other solutions or build something yourself.

FirebaseError when logging out of web app, exception thrown by user callback, document references must have an even number of segments

I've built a Javascript web app using Firestore and Firebase. When logging the user out, I am getting console errors. The errors reference the firebase-database.js and firebase-firestore.js scripts, though, so I can't really tell what is happening:
[2020-05-22T12:32:58.436Z] #firebase/database: FIREBASE WARNING:
Exception was thrown by user callback.
Hr#https://www.gstatic.com/firebasejs/7.6.1/firebase-firestore.js:1:48219
firebase-database.js:1:11297
FirebaseError: Invalid document reference. Document references must
have an even number of segments, but user has 1
firebase-firestore.js:1:48219
This is my log out function:
$('.logout').on('click', function(){
firebase.auth().signOut()
.catch(function(error){
console.log(error.code);
console.log(error.message);
});
});
Then I have a listener for firebase.auth().onAuthStateChanged which triggers this:
firestoredb.collection('user').doc(uid).update({
status: false,
last_changed: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(){
uid='';
$('#screenname').html('');
window.location='https://www.example.com/your-account.asp?task=logout&afterlogin=%2Fv2';
})
.catch(function(error){
console.log(error.code);
console.log(error.message);
});
What might be my strategy for tracking down this error since the console logs are not that helpful? The error does not really affect the performance of the app, since the user is logged out anyway (and redirected via Javascript), however it bothers me that there is an error.
EDIT: I am wondering if the cloud script that is running could be the problem. That might explain why I cannot identify the line number and why the error message is so vague. Here is my cloud script, can this be modified so that a missing UID value would be ignored? This is basically the script provided by Google for combining Firebase and Firestore to maintain session state of the user.
const functions=require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp();
const firestore=admin.firestore();
exports.onUserStatusChanged=functions.database.ref('user/{uid}').onUpdate(
async (change, context) => {
const eventStatus=change.after.val();
const userStatusFirestoreRef=firestore.doc(`user/${context.params.uid}`);
const statusSnapshot=await change.after.ref.once('value');
const status=statusSnapshot.val();
if (status.last_changed>eventStatus.last_changed){
return null;
}
eventStatus.last_changed=new Date(eventStatus.last_changed);
return userStatusFirestoreRef.update(eventStatus);
}
);

When using auth0, I cannot gain access to the scope read:current_user

I would like to be able to view and update a user's metadata from a single page application but whenever I attempt to gain access to any of the scopes that would appear from the documentation (https://auth0.com/docs/libraries/auth0js/v9)
However, when I run the following code:
webAuth.checkSession(
{
audience: `https://mysite.eu.auth0.com/api/v2/`,
scope: "read:current_user"
},
(err, result) => {
err && console.log("err", err");
result && console.log("result", result);
}
);
I get the following error:
{error: "consent_required", error_description: "Consent required"}
I've tried putting the scope read:current_user in multiple places but it always appears to fail.
The error means that the server is requesting an additional consent from the user, so checkSession cannot complete the action because it happens silently and cannot prompt the user.
To fix this, go to Auth0 dashboard -> APIs -> Auth0 Management API -> Settings tab -> uncheck 'Allow Skipping User Consent'.

PouchDB and React-Native not replicating .to() but .from() is working

For some reason documents created on my app are not showing up on my remote couchdb database.
I am using the following
import PouchDB from 'pouchdb-react-native'
let company_id = await AsyncStorage.getItem('company_id');
let device_db = new PouchDB(company_id, {auto_compaction: true});
let remote_db = new PouchDB('https://'+API_KEY+'#'+SERVER+'/'+company_id, {ajax: {timeout: 180000}});
device_db.replicate.to(remote_db).then((resp) => {
console.log(JSON.stringify(resp));
console.log("Device to Remote Server - Success");
return resp;
}, (error) => {
console.log("Device to Remote Server - Error");
return false;
});
I get a successful response the response:
{
"ok":true,
"start_time":"2018-05-17T15:19:05.179Z",
"docs_read":0,
"docs_written":0,
"doc_write_failures":0,
"errors":[
],
"last_seq":355,
"status":"complete",
"end_time":"2018-05-17T15:19:05.555Z"
}
When I go to my remote database, document_id's that am able to search and grab on the application do not show up.
Is there something I am not taking into account?
Is there anything I can do to check why this might be happening?
This worked when I used the same scripting method in Ionic and when I switched to React-Native I noticed this is the case.
NOTE: When I do .from() and get data from remote to the device, I get the data. For some reason it just isn't pushing data out
"Is there anything I can do to check why this might be happening?"
I would try switching on debugging as outlined here.
PouchDB.debug.enable('*');
This should allow you to view debug messages in your browser's JavaScript console.

Can't login to Skype SDK with non-existing domain name

I have problem about SigninManager. When I login in with tan.tastan#abcd.com, abdc.com is a reachable domain. But if I write a wrong domain, for example tan.tastan#abcd***E***.com, I am not getting a response and my application is waiting. Nothing happens and there is no return error code.
Here is my sample code, settings includes username, password, and domain information.
function doLogin(settings) {
return new Promise((resolve, reject) => {
window.skypeWebSDKApi.signInManager.signIn(settings).then((response) => {
resolve(response);
}, (error) => {
reject(error);
}).catch(reject);
});
}
What is the problem?
It's hard to know exactly what is going on without seeing the contents of settings but I suspect you're issue here is a promise not getting resolves. Try simplifying your call:
function doLogin(settings) {
var app = new api.application;
app.signInManager.signIn(settings).then(function () {
console.log('success');
}, function (error) {
console.log(error);
});
}
I've been using the SDK for quite a while now and this is my experience:
When trying to log in using a non existing domain, the Web SDK never returns an error. I've tried different SDK versions and both General Availability and Public Preview API keys.
I ended up starting my own signin timer when trying to sign in.
When no response is received within 20 seconds, I send a signOut request (which cancels the sign in) and show a message to the user (Please make sure you've entered the right username etc..).
It's really lame to have a workaround like this but unfortunately I haven't found a better way yet to deal with this issue, also assuming Microsoft is not going to fix this anymore...

Categories

Resources