How do I determine if asyncstorage is in
Error rejection
if (await AsyncStorage.getItem("id") == undefined){
alert("yes");
}
If you are trying to check for a failed getItem call (happened to me on simulator, had to reinstall the app for it to work again), you can try to wrap your code in a try-catch, this way :
try {
if (await AsyncStorage.getItem("id") == undefined){
alert("item not found ");
}
} catch(error) {
console.log("getItem function failed", error)
}
A more elegant way of achieving this would be:
const id = await AsyncStorage.getItem("id") // Get the item reference of ID if exists
if (id) {
// Do what you want if ID is actually there
} else {
// Do what you want if ID is not there
}
Related
I am new to coding and trying to build an APi using NOde js, express and mongodb
here is my code
router.get('/:id', async(req, res) => {
console.log(req.params.id);
try{
const show = await Show.findById(req.params.id);
const _iD = show._id.toHexString()
console.log(_iD );
if(req.params.id === _iD){
res.json(show);
} else {
res.send("not right ID");
}
}
catch(err){
console.log("error" + err)
}
})
it not working out,if "you enter a wrong ID intentionally " and should get " not right ID ", but it gets "Cast to Object ID failed for value".
Try out this function
function isMongooseId(id) {
var valid = false;
try{
if(id == mongoose.Types.ObjectId(""+id)) valid = true;
} catch(e){
valid = false;
}
return valid;
}
// You can use it like this,
if(isMongooseId(req.params.id)) {
// Perform your db operation
}
Make sure the "intentionally wrong ID" still respect the objectId syntax (24 hexadecimal characters i would say). Otherwise you will fail at the Show.findById and jump right into the catch.
Then, i'm not sure of what your trying to do.
If you provide an ID that is not present in the collection, Show.findById will not return any object so you won't be able to get its ID with show._id.toHexString() and you will, again, jump to the catch.
And if the ID is in the collection, req.params.id === _iD will always be true and you will never reach the else.
Instead you should just check if show contain an object
I have this function which is a search query. This works fine unless the query string name is not detailed enough which then throws up an error message
request( url, function (error, data) {
errorText = arguments['0'];
if (error) {
callback('Unable to connect to location services!', undefined)
} else if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
}
else {
callback( {
data = data.body,
namePlace: data.suggestions[1].entities[0].name,
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
})
The error message from the console is
namePlace: data.suggestions[1].entities[0].name,
^
TypeError: Cannot read property 'name' of undefined
I want to be able to capture this error message and callback 'Unable to find location, try another search.'
It sounds like what you want to check for is whether data.suggestions[1].entities has any entries. Perhaps something like:
else if (data.suggestions[1].entities.length === 0) {
callback('Unable to find location, try another search.', undefined)
}
Depending on how reliable the resulting data structure is, you might also check for null or undefined values. But for this particular error it looks like entities is defined and an array but just has no entries.
You need to change the logical order of the first if, otherwise else if (error) will prevent if (errorText.includes('Cannot read property')).
Have you previously defined let request = new Request(<uri>)?
What is it that you're trying to do?
request( url, function (error, data) {
errorText = arguments['0']; // What are you trying to do here?
if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
} else if (error) {
callback('Unable to connect to location services!', undefined)
} else {
callback( {
data = data.body, // What are you trying to do here?
namePlace: data.suggestions[1].entities[0].name, // What are you trying to do here?
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
}); // <- semicolon here
I am getting this error while trying to store data in AsyncStorage in react native and the data are also not getting added to the storage
Possible Unhandled Promise
Rejection (id: 0): Error: com.facebook.react.bridge.ReadableNativeMap
cannot be cast to java.lang.String Error:
com.facebook.react.bridge.ReadableNativeMap cannot be cast to
java.lang.String*
My code is like this
//Public methods
static addProduct(id,name,qnty){
let product={
id:id,
name:name,
qty:qnty,
};
let cartResponse={};
product.rowId = this.generateHash(hashItem);
AsyncStorage.getItem('CART').then((data) => {
//Check if the product already in the cartTotalItem
if (data !== null && data.length>0) {
if (this.checkIfExist(product.rowId)) {
//Update product quantity
data[product.rowId]['qty'] += product.qty;
}else{
//Add add product to the storage
data[product.rowId] = product;
}
//Update storage with new data
AsyncStorage.setItem("CART", data);
cartResponse = data;
}else{
let cartItem ={};
cartItem[product.rowId] =product;
AsyncStorage.setItem("CART", cartItem);
cartResponse =cartItem;
}
return true;
}).catch(error => {
console.log("Getting cart data error",error);
return false;
});
}
I tried to look for solution and i found few links out of which this,
Possible Unhandled Promise Rejection (id:0) Warning kinda old, but has same problem as me.
I tried to apply the same solution from the thread but that did not fix the issue.
Can anyone please help? ? Thank you.
The error is caused by setItem function. setItem is also returns a promise and your value should be a string.
Sample
AsyncStorage.setItem("CART", JSON.stringify(cartItem));
The promise chain can be confusing. The underlying problem is that the internal Promise rejection isn't chained to the external Promise.
const test = flag => {
return Promise.resolve('Happy')
.then(msg => {
if (flag === 0) return msg;
if (flag === 1) return Promise.reject('Kaboom!');
if (flag === 2) Promise.reject('Crash!');
})
.catch(err => {
return `Error: ${err}`;
});
};
test(0).then(res => log(res)); //'Happy'
test(1).then(res => log(res)); //'Error: Kaboom!'
test(2).then(res => log(res)); //'undefined' then UnhandledPromiseRejectionWarning
In the examples above, (0) exits without error, (1) rejects in a chained way by returning the inner Promise, (2) exits without error but then shows the annoying warning.
So the problem block in the original code should be:
if (data !== null && data.length>0) {
if (this.checkIfExist(product.rowId)) {
//Update product quantity
data[product.rowId]['qty'] += product.qty;
} else {
//Add add product to the storage
data[product.rowId] = product;
}
//Update storage with new data
cartResponse = data;
return AsyncStorage.setItem("CART", data); //chain the promises
} else {
let cartItem ={};
cartItem[product.rowId] =product;
cartResponse =cartItem;
return AsyncStorage.setItem("CART", cartItem); //chain the promises
}
By returning the AsyncStorage.setItem(...) result the outer catch can handle the error.
I realise this is an old post, but this issue confused me in the past. Hopefully this will clarify things for others.
I'm working on some authentication in React using Firebase as the backend.
I have a function to check if a user exists that works as I expect:
checkIfUserExists(uid) {
ref.child('users').child(uid).once('value', function(snapshot) {
if (snapshot.exists()) {
console.log("User exists");
return true;
} else {
console.log("User does not exist");
return false;
}
});
}
When I call it passing a uid, it will write to the console if the user exists or not.
this.checkIfUserExists(userId);
I want to just get a boolean representation of whether the user is logged in or not, but trying to do something like this will always print "No user".
if (this.checkIfUserExists(userId)) {
console.log('The user does really exist');
} else {
console.log('No user');
}
If i try to
console.log(this.checkIfUserExists(userId));
The console outputs "undefined".
Am i approaching this the wrong way? Why is it undefined?
The return statement inside the inner function will not return the value through the outer function. Instead try sending a function like this
checkIfUserExists(uid, callback) {
ref.child('users').child(uid).once('value', function(snapshot) {
callback.call(null, snapshot.exists());
});
};
checkIfUserExists(uid, function(exists){
if(exists){
console.log("User exists");
}else{
console.log("User does not exist");
}
});
More on .call() here in documentation
I have this function, for example:
app.get('/', function(req, res) {
var token = req.query.token;
if(!token) {
res.render('auth'); // Authentication
} else {
authorizedUsers.forEach(function(user) {
if(user.id == token) {
console.log('found, nickname: ' + user.nickname);
return true;
}
});
console.log('not found');
return false;
}
});
Basically it's looping through the authorizedUsers array, and looking for an entry where entry.id equals the token variable.
What I wanted to do is, if found, to return true and stop the execution of the rest of the app.get('/')... block.
If not found, obviously the forEach loop has already gone through all entries, and eventually the execution arrives to the printing of "not found" and return false;.
For my current code, even though an entry is found, execution continues and I still get the 'not found' log.
Am I missing anything?
To simplify things, what I wanna do is:
Looping through all authorizedUsers entries, comparing entry.id to the token variable.
If found, print "found" to the console and stop the execution.
If not found, print "not found" to the console and stop the
execution.
Thank you.
Edit
Following Michael's solution, this is my working code:
app.get('/', function(req, res) {
var token = req.query.token;
if(!token) {
res.render('auth'); // Authentication
} else {
if(!authorizedUsers.some(function(user) {
if(user.id == token)
return true;
})) {
console.log('No entries found.');
} else {
console.log('Entries found!');
}
}
});
You would use Array.prototype.some for this:
authorizedUsers.some(function(user) {
return user.id == token;
}
The some() method tests whether some element in the array passes the test implemented by the provided function.
The forEach function cannot be interrupted unless the code inside throws an exception.
So you could either do something like this
Or just let it run through all the records doing something like this:
var found = false;
authorizedUsers.forEach(function(user) {
if(user.id == token) found = true;
});
console.log('found? ', found);