I'm trying to access a data object that is referenced by a key. In this case, we have "applicant" data nested within an Event. I'm trying to create a new object with that data. I can access top-level Event data and the key for each applicant, but I can't figure out how to access applicant data - for example, application date, notes, and status.
I'd like to say something like applicationStatus = key.status, but that doesn't work.
onCreateApplication () {
fb.eventsCollection.orderBy('startDate', 'desc').onSnapshot(querySnapshot => {
let appsArray = []
querySnapshot.forEach(doc => {
let event = doc.data()
let eventId = doc.data().id
let eventTitle = doc.data().title
let eventSlug = doc.data().slug
let applications = doc.data().applicants
let appStatus = doc.data().applicants.status
for (var key in doc.data().applicants) {
let eventData = {
id: eventId,
title: eventTitle,
slug: eventSlug
}
let userData = {
id: key
}
let application = {
event: eventData,
user: userData,
status: key.status????????,
appliedDate: key.created??????
}
fb.applicationsCollection.add(application)
}
})
})
},
This is my best guess as to what is going on with your data structure. I hope this helps and please comment to clarify anything else.
onCreateApplication(){
fb.eventsCollection.orderBy('startDate', 'desc').onSnapshot(querySnapshot => {
querySnapshot.forEach(doc => {
let data = doc.data();
let applications = Object.keys(data.applicants).map(function(id){
let application = {
event: {
id: data.id,
title: data.title,
slug: data.slug
},
user: {
id: id
},
status: data.applicants[id].status,
appliedDate: data.applicants[id].created
})
fb.applicationsCollection.add(application);
return application;
})
})
})
}
Related
So, i have this code:
client.on("messageCreate", async (msg) => {
if (msg.content.startsWith("-p")) {
if (!msg.member.voice?.channel) return msg.channel.send("Por favor...");
const connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator,
});
google
.youtube("v3")
.search.list({
key: process.env.YOUTUBE_TOKEN,
part: "id",
q: msg.content.slice(3),
maxResults: 1,
})
.then((response) => {
const { data } = response;
let link = "https://www.youtube.com/watch?v=" + data.items.id.videoId;
});
let args = msg.content.slice(3);
let stream = await play.stream(args);
let resource = createAudioResource(stream.stream, {
inputType: stream.type,
});
let player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
player.play(resource);
connection.subscribe(player);
}
});
And I would like to use the value of the variable "link", which is a string, as a parameter for the method play.stre(args)
I'm don't fully understand how to get that done
Also, if possible I would like to find a way to store that value too inside an array outside the whole:
*client.on('messageCreate' , async msg => {... ...})*
You most likely want to call play.stream from within the then callback of list:
google.youtube("v3")
.search.list({
key: process.env.YOUTUBE_TOKEN,
part: "id",
q: msg.content.slice(3),
maxResults: 1,
})
.then(async (response) => {
const { data } = response;
let link = "https://www.youtube.com/watch?v=" + data.items.id.videoId;
let stream = await play.stream(link);
});
Like this, you'll make sure that you actually have a value set for link when using it to call stream.
I have API query and getting the result and setting those in a state variable in Oncompleted method of API query, Now i am updating the same state variable in another api query "onCompleted method.
I am not able to access the result from state what i have set before in first api query and below is my code
Query 1:
const designHubQueryOnCompleted = designHubProject => {
if (designHubProject) {
const {
name,
spaceTypes
} = designHubProject;
updateState(draft => { // setting state here
draft.projectName = name;
draft.spaceTypes = (spaceTypes || []).map(po => {
const obj = getTargetObject(po);
return {
id: po.id,
name: obj.name,
category: obj.librarySpaceTypeCategory?.name,
description: obj.description,
warning: null // trying to modify this variable result in another query
};
});
});
}
};
const { projectDataLoading, projectDataError } = useProjectDataQuery(
projectNumber,
DESIGNHUB_PROJECT_SPACE_TYPES_MIN,
({ designHubProjects }) => designHubQueryOnCompleted(designHubProjects[0])
);
Query 2:
const {
// data: designhubProjectSpaceTypeWarnings,
loading: designhubProjectSpaceTypeWarningsLoading,
error: designhubProjectSpaceTypeWarningsError
} = useQuery(DESIGNHUB_PROJECT_LINKED_SPACETYPE_WARNINGS, {
variables: {
where: {
projectNumber: { eq: projectNumber }
}
},
onCompleted: data => {
const projectSpaceTypeWarnings = data.designHubProjectLinkedSpaceTypeWarnings[0];
const warnings = projectSpaceTypeWarnings.spaceTypeWarnings.reduce((acc, item) => {
const spaceTypeIdWithWarningState = {
spaceTypeId: item.spaceTypeProjectObjectId,
isInWarningState: item.isInWarningState
};
acc.push(spaceTypeIdWithWarningState);
return acc;
}, []);
console.log(state.spaceTypes); // trying to access the state here but getting empty array
if (state.spaceTypes.length > 0) {
const updatedSpaceTypes = state.spaceTypes;
updatedSpaceTypes.forEach(item => {
const spaceTypeWarning = { ...item };
spaceTypeWarning.warning = warnings?.filter(
w => w.spaceTypeId === spaceTypeWarning.id
).isInWarningState;
return spaceTypeWarning;
});
updateState(draft => {
draft.spaceTypes = updatedSpaceTypes;
});
}
}
});
Could any one please let me know where I am doing wrong with above code Or any other approach to modify the state, Many thanks in advance!!
It will come at some point that perhaps I will have to update more than 500 documents, but first I have to read and update all the data to be fine. How would you do this with transactions?
I did something similar with _.chunk with batch. But this time I need a transaction but I wouldn't know how to do.
transaction:
if (previousValue.Name !== newValue.Name || previousValue.Image !== newValue.Image) {
const chatRoomQuery = db.collection(chatsCollection).where(userIdsProperty, 'array-contains', userId);
const transactions = _.chunk(chatRoomQuery, maxSize) => {
return db.runTransaction(transaction => {
return transaction.getAll(chatRoomQuery).then(docs => {
docs.forEach(doc => {
let chatRoom = doc.data();
let oldUser = {
Id: previousValue.Id,
Name: previousValue.Name,
Image: previousValue.Image
};
let newUser = {
Id: newValue.Id,
Name: newValue.Name,
Image: newValue.Image
};
let index = chatRoom.Users.indexOf(oldUser);
if (index > -1) {
chatRoom.Users.splice(index, 1, newUser);
transaction.update(doc.ref, chatRoom)
}
})
})
})
});
await Promise.all(transactions);
}
I think I have a syntax error not getting it right.
I leave a screenshot.
I can retrieve data from a Firebase database, but when I try to assign the fetched data from the database, the object properties require you to invoke a getter (I mean I can't access them after assignment)
This is the Vue instance.
Yes, I know. This is formatted weirdly, this is something that VS Code does for me...
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
this.users.push(user);
console.log(this.users);
});
});
}
};
When I open up the console I need to click on three dots to get the actual data.
The following should do the trick:
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
let usersArray = [];
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
usersArray.push(user);
});
this.users = usersArray;
console.log(this.users);
});
}
};
I want to get the Key generated when I push data to Firebase database. I want to handle them with my own function,
So the issue is when the user fills the form he sends the data to our real-time DB, contained in this data are some images (optional), and I don't need to let the image object empty in DB, so how to handle this, and when the user needs to send an image I want to save this image in the same Order, not in New Order.
Node
Here is my function
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({ // didn't updated the key generated just add new element with new key !!
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: response });
}
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
}
});
};
This seems to work fine for me:
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
console.log("new key: "+newChildRef.key);
ref.child(newChildRef.key).update({ secondChild: true });
After running this code, I end up with this JSON in the new child whose key gets logged:
"-LdgLWu_wBNNicFlPDGj" : {
"firstChild" : true,
"secondChild" : true
}
Live demo: https://jsbin.com/hovoleh/edit?js,console
Live JSON: https://stackoverflow.firebaseio.com/55912103.json?print=pretty
Update: if you just want to write both the existing data and new data to a new location:
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({
nameOfProblem: nameOfProblem,
description: description,
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
The push ID from any Firebase snapshot ref is in ref.name().
I know it's been a while since the author created a post but maybe someone will find it useful.
The above answers are a bit wrong because, for example, after: newChildRef
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
newChildRef <--- promise
ref = rdb.ref('name_of_your_ref');
var childRef = ref.push({
IdUser: currentUserId,
ProductCategory: pCategory,
ProductDescription: pDesc,
ProductId: pId,
ProductName: pName,
ProductPrice: pPrice,
ProductQuantity: pQuan
}).catch(err => console.log(err.message));
childRef.then(item => {
ref.child(item.key).update({
IdKey: item.key
}).then(() => history.push('/delivery/basket'));
});
Greetings, Matthew