I have a MySQL Database with an array called connectionList . The array for a user contain several objects with a senderID and receiverID fields and would sometimes be empty if the user has no pending connection request.
I have successfully mapped through the array to fetch out the data to the browser. I am however having issues when I have to use the ifelse statement to make a button toggle between connect if the connectionList array is empty or doesn't contain a senderID that matches the id of the logged in user and connected if the array contains an object having a senderID id that matches the id of the logged in user. I need assistance on what to do.
What I have done
{connectionList && connectionList.map(function (conn){
if(conn.senderID === user.id){
return <>Connected</>
} else {
return <>Connect</>
}
})}
You can use optional chaining (?.) in combination with some: The .some(conn => conn.senderID === user.id) checks if the callback is true for at least one element in it (in your case at least one connection is from the current user). The ?. is an optional shortcut which returns undefined if connectionList is undefined or will call the method if it's not undefined.
Together this will return <Connected> if at least one connection sender is the current user, else <Connect>.
{
connectionList?.some(conn => conn.senderID === user.id) ?
<Connected>
: <Connect>
}
On a side note: you don't want to use .map except if you want one result per element in the list. In your case you only want one result for the whole list.
You can achieve it by below code
{
connectionList ?
<>
{connectionList.map(conn => {
<>
{conn.senderID === user.id ?
<>Connected</>
:
<>Connect</>
}
</>
})}
</>
:
<>Connect</>
}
Related
I'm subscribing to a method in Angular using typescript, which is a simple post Call that returns an entire HTTP Response. I'm wanting to create a simple conditional that checks to see if a certain key exists in the HTTP response. The conditional will work with an object that contains the key, but for an object that doesn't contain the key it throws an undefined.
Is there a way to omit the error or exception thrown and to proceed to the else portion
The keys of the object body are added if the user includes a number, without that it doesn't exist with the PhoneNumber key value
what I've tried / flipped the if and else
!= undefined (vice versa)
== null (vice versa)
this.postMyName(userInfo).subscribe(
(result:Response) => {
if (result['body']['user'].hasOwnProperty(['PhoneNumber'])) {
console.log("User has included a phoneNumber");
} else {
console.log("User has Not included a phoneNumber");
}
},error ...)
You can also try this solution maybe it will work
this.postMyName(userInfo).subscribe(
(result:Response) => {
if ('PhoneNumber' in result['body']['user'])) {
console.log("User has included a phoneNumber");
} else {
console.log("User has Not included a phoneNumber");
}
},error ...)
How can i make my code search for two user ids but take in consideration if its more users?
lets say my db only contains a conv with user 10 and 4.
my code:
return Conversations.findOne({"users.userid": { $in: SearchUsers }}).then(function (response) {
return response;
});
Test 1: users with ids: [10,4] -> would return the conversation. aka ( true)
test 2: users with ids [10,4,8] -> This example would NOT return it. Even that both 10 and 4 is in the users, cause there is more members in it, and therefore not a private for them alone. , because it does not have an match, even that 10 and 4 is there, there is a user with id 8, and it dosent exist. ( false )
The idea is to make like facebook has, group chat system, and in this particular matter, to check if an conversation exists or not.
Ideally the $searchUsers could contain anything from 1-50+ userids, and i need it returned if all the users are in a match, if not all is in it, then it wont return any.
tryThe $all operator : it should behave like an $and with $in
Conversations.findOne({"users.userid": { $all: SearchUsers }}).then(function (response) {
return response;
});
so im trying to get my bot to detect a user id to allow a command so a command for only one user and im having a bit of trouble understanding what i am doing wrong
run(message) {
//member id 184191493919997952
if(message.member.id.find('id', '184191493919997952')){
return message.say('True')
}else{
return message.say('False')
}
}}
so ive tried to set it up to check whoever used the command and if their snowflake id isnt equal to the one listed then it should return false but i keep getting a TypeError am i missing something?
ID is a property of User (which is message.author).
You can directly use "==" to check if it equals to something.
run(message) {
if (message.author.id == "184191493919997952") {
message.reply("true")
} else {
message.reply("false")
};
};
https://discord.js.org/#/docs/main/stable/class/User?scrollTo=id
Also, there is no method called "say" of message.
You can check available methods here (for example, message.reply()):
https://discord.js.org/#/docs/main/stable/class/Message
i want to search for a specific user in the ref(likers) then remove it but it won't work here and it alert "likers" when i alert(this.liker) not the user key in the ref(user)
here is the database
and here is the code
firebase.database().ref('posts/-M13xC_yeIsj342A75pz/likers')
.orderByChild('user')
.equalTo('fHI1izTOJ5VeC7ZnjXUducickzj1'/* 'PCrBx38NcjZdsgmRS805sk7lgWn1' firebase.auth().currentUser || {}).uid */)
.on('value', snap => {
this.liker = snap.key
alert(this.liker)
})
firebase.database().ref('posts').child(this.props.postKey/*'-M0IviCqMGE_PxoqNd0W'*/).child('likers').child(key).remove()
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
You code need to handle this fact, by looping over the child nodes of the snapshot you get.
firebase.database().ref('posts/-M13xC_yeIsj342A75pz/likers')
.orderByChild('user')
.equalTo('fHI1izTOJ5VeC7ZnjXUducickzj1'/* 'PCrBx38NcjZdsgmRS805sk7lgWn1' firebase.auth().currentUser || {}).uid */)
.once('value', results => {
results.forEach((snapshot) => {
alert(snapshot.key)
});
})
In the above, I also changed the code to use once instead of on. This won't make any difference to the query results, but means it stops listening after it gets the query results.
I'm creating a sign in method that is trying to check if my current user has agreed to my terms of agreement after verifying their email address. My function is as follows:
SignIn(email, password) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then(cred => {
this.ngZone.run(() => {
// Gets current signed in user.
this.afAuth.authState.subscribe(user => {
// Queries Details subcollection.
this.db.collection('users').doc(user.uid).collection('Details')
.get().toPromise().then(
doc => {
if (user.termsOfAgreement == false) {
this.router.navigate(['terms']);
} else {
this.router.navigate(['dashboard']);
}
})
})
});
}).catch((error) => {
window.alert(error.message)
})
}
I know that I'm getting the firebase user object and that it doesn't contain my specific sub collection field names (i.e. user.termsOfAgreement). But how would I access those? I'm trying to check if my termsOfAgreement field is true or false.
My Firestore User Collection state on sign up
User (Collection)
- lastLogin: timestamp
- name: string
- userId: string
Details (subcollection)
- termsOfAgreement: false
First note that this.db.collection('users').doc(user.uid).collection('Details') is not a collection group query, but a read operation on a single collection.
It sounds like you want to check if the Details collection under the user document contains a document with termsOfAgreement equal to true. You can most easily check that with:
firebase.firestore()
.collection('users').doc(user.uid)
.collection('Details').where('termsOfAgreement', '==', true).limit(1)
.get().then((querySnapshot) => {
if (querySnapshot.empty == false) {
this.router.navigate(['terms']);
} else {
this.router.navigate(['dashboard']);
}
})
The above code is using the regular JavaScript SDK, as there is no need to use AngularFire for this operation. But aside from that, it'd work the same in either: you fire a query against the collection and then check if there's any results.
In addition to fixing your code, this also optimizes it in two ways:
The query is sent to the server, so that you're only transferring data that matches the condition.
At most one document is transferred, since you only care whether any result exists.
I'm not sure why you're storing termsOfAgreement in the subcollection though.
If you're checking for the existence of any subdocument where the termsOfAgreement is true, you might want to consider adding a termsOfAgreement field to the user document itself, so that you don't need to perform a query across the subcollection.
You'd set this userDoc.termsOfAgreement to true once the user accepts any terms in the subcollection, and then won't have to query the subcollection anymore (simplifying the reading code and reducing the number of read operations).