Setting a new relation in EmberJS without original model - javascript

So I have a model created/loaded normally:
let contact = self.get('store').createRecord('contact');
I then get the address, which is a BelongsTo relation on the model:
let address = contact.get('address');
the returned address variable is a Proxy object, which the promise resolves as either the related model or null.
The question is how can I create a new address model and assign it to the original contact object, but with only the address proxy object?

If you want to create a new address record (and not model) and assigning it to your newly created contact, you can do the following:
const store = this.get('store');
const contact = store.createRecord(
'contact',
{
name: 'Jack',
address: store.createRecord('address')
}
);
or if you already have an address proxy and you want to create a new one only if it results to null:
const store = this.get('store');
const contact = store.createRecord('contact', { name: 'Jack' });
my_address_proxy.then(address => {
contact.set('address', address || store.createRecord('address'));
});

Related

How to create a new many to many reference in Javascript?

Imagine I have one user and one other user. The former would like to follow the latter, which I have designed as a many to many relashionship. How can I do it in Javascript? I need something like user.followers.append(other).
In real life you use database connections for that, and you must have a backend already built. But if you're just playing with objects in JS, then you need a User class with a follow method.
function User (params) => {
const {
name,
age,
friends = []
} = params
this.name = name
this.age = age
this.friends = friends
this.follow = (newFriend) => {
this.friends.append(newFriend)
}
this.showFriends = () => {
console.log(this.friends)
}
}
Then you create two users.
const user = new User({
name: "Joe",
age: 25
})
const other = new User({
name: "Francis",
age: 27
})
Then you make one dude follow the other.
user.follow(other)
Then you can log the user's friends to see what's up.
user.showFriends()
Make user.followers as array. So that you can push the userid of the user who is trying to follow them.
Eg:
user = {'id': 'current_user_id',
'followers' : ['user_id_1', 'user_id_2'....]
};

How to store an objects in array after method in my class

Please see my code below.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
addUser() {
users.push(this.name, this.email)
}
}
const userOne = new User ('John', 'john#mail.com');
const userTwo = new User ("Alan", "alan#mail.com");
let users = [];
userOne.addUser();
userTwo.addUser();
After method addUser i have array with names and emails but i would like to have an array with objects as below
users = [
{ name: 'John', email: 'john#mail.com' }
{ name: 'Alan', email: 'alan#mail.com' }
]
How my method addUser should looks in my prototype and if variable users is in correct place or can be store somewhere in Class?
Thanks in advance
You're pushing the object properties one after the other, rather than as an object together.
Try this for your addUser method:
addUser() {
users.push({name: this.name, email: this.email})
}
You just need to push each proprieties
users.push({name: this.name, email: this.email})
If you want to do this automatically you can use:
users.push(Object.assign({}, this))
Or you cloud just pass the whole object:
users.push(this)
Anyhow, I would suggest not to use users globally.

Adding Objects to another object

I'm trying to add object inside an object with id as a key in react provider. Following is the use case.
const [memberList, setMemberList] = useState({
homeTeam: [],
awayTeam: [],
homeTeamClone: {},
});
I can successfully add member to an array, however I'm more keen to add that in homeTeamClone object.
example of object = {"id":"3a21b0a-1223-46-5abe-67b653be5704","memberName":"Adam"}
I want final result as
homeTeamClone: {
"3a21b0a-1223-46-5abe-67b653be5704": {"id":"3a21b0a-1223-46-5abe-67b653be5704","memberName":"Adam"},
"3a21b0a-1223-46-5abe-67b653be5705": {"id":"3a21b0a-1223-46-5abe-67b653be5705","memberName":"Chris"},
"3a21b0a-1223-46-5abe-67b653be5706": {"id":"3a21b0a-1223-46-5abe-67b653be5706","memberName":"Martin"},
}
I tried Object.assign(homeTeamClone, member) but did not get the expected result.
Thanks in Advance.
If the question is how to set individual member than you can do this:
const member = { id: '3a21b0a-1223-46-5abe-67b653be5704', memberName: 'Adam' };
setMemberList({
...memberList,
homeTeamClone: {
...memberList.homeTeamClone,
[member.id]: member,
},
});
In this case spread all old values and add new one. (In case user with same ID is added again, object value will be from the new one)

On Firebase, why does remove work on push but not on set?

I'm trying to write on Firebase an object with this structure and when a user reloads or leaves page, the user's data will be removed from Firebase.
/users {
1: {name: name, win: win},
2: {name: name, win: win}
}
This code does that but generates random Id each push so I cannot interfere with each user's data later:
var database = firebase.database();
var userRef = database.ref("/users");
function createNewUser() {
var newUser = $('#newUser').val().trim();
if (newUser) {
var con = userRef.push({
name: newUser,
win: 0,
loss: 0
});
con.onDisconnect().remove();
}
else {
return;
}
}
$('#startButton').on('click', createNewUser);
This code is similar but has error:
onDisconnect is not a function
function createNewUser() {
var newUser = $('#newUser').val().trim();
if (newUser) {
var con = database.ref('users/ + 1).set({
name: newUser,
win: 0,
loss: 0
});
con.onDisconnect().remove();
}
else {
return;
}
}
If I use push, I can retrieve each user's ID but I still won't be able to change user's data, especially if 1 of the 2 users leaves.
When using .push, Firebase will always generate a random key for this new entry.
You can use .set instead of .push and you'll need to add to the path/ref a unique identifier for each user, like userName or userId as userRef.child('/userid').set
Or you can capture the new entry after creation, and get the new generated random key, and then use it for the .remove
See Firebase Documentation here
Hope that helps.
All the best.

How to retrieve Firebase pushed key?

I have an event I'm storing in my database. It is stored as
events
my_party123
info
-KZbdiR_PBrAwxYvUR4U
name: 'John'
city: 'Los Angeles'
my_party124
...
However, I'm trying to retrieve this info and I can't quite get it.
I tried
ref
.child('events')
.child('my_party123') // I also tried .push('my_party123')
.once('value')
.then(snapshot => {
console.log(snapshot.key) // my_party123
console.log(snapshot.val().info)
// this shows object with
// "-KZbdiR_PBrAwxYvUR4U" property, this is the pushed key property
im trying to access
})
.pushed is creating new keys when i called it - how do i just access the value stored in my database?
If you're looking to have unique event URLs that point at events, I'd recommend a change to your data structure to be something more like:
events
-KZ123PUSHID
name: 'John'
location: 'Los Angeles'
-KZ124PUSHID
name: 'Morgan'
location: 'New York City'
eventNames
my_party_123: '-KZ123PUSHID'
sweet_nyc_part: '-KZ124PUSHID'
Then, in your code, you could do something like:
var eventNamesRef = firebase.database().ref('eventNames');
var eventsRef = firebase.database().ref('events');
var event;
eventNamesRef.child(nameFromUrl).once('value').then(nameSnap => {
eventsRef.child(nameSnap.val()).on('value', eventSnap => {
event = eventSnap.val();
});
});

Categories

Resources