How to add a Promise .then() to an Array.push? - javascript

I have an array however, one of the object children needs to get data from another location in my Firebase Database to show in the array. This requires a Promise.
How do I show the data from the Promise in the array?
getListofReferrers() {
//
//
// Getting list of referrers from Firebase.
this.eventData.getReferrersList().on('value', snapshot => {
let rawList98 = [];
snapshot.forEach(snap => {
// Bringing the information over into a local array to show on the page.
rawList98.unshift({
id: snap.key,
text: this.eventData.getOtherNameExternal(snap.val().userid).then( (v)=> {return v}),
userid: snap.val().userid,
username: snap.val().username,
email: snap.val().useremail,
referralPoints: this.eventData.numberWithCommas(this.eventData.getOtherProfileProperty(snap.val().userid, "referralPoints") || 0),
});
})
// Taking the information into a "this." variable
this.referralList = rawList98;
console.log(this.referralList);
});
}
I keep getting: [object Promise] when showing the "username" value.
In console.log(rawList98); however, I get the following:
email: "pjoc#pjaguar.com"
id: "referrer9OxMTyUDfiXrLp9O65XW0hUbHgH2"
referralPoints: "0"
username: t
__zone_symbol__state: true
__zone_symbol__value: "John Doe"
[[Prototype]]: Object
userid: "9OxMTyUDfiXrLp9O65XW0hUbHgH2"
How come it's showing the value received from the Promise but I can't capture that in the .then() to properly assign to the child "username"? I will need to call this Promise getting the username for every node in the Firebase Database

Since you need to wait for the username to be available before you can construct the object, you need to put the code inside the .then:
this.eventData.getUserName(snap.val().userid).then(v => {
rawList98.unshift({
id: snap.key,
username: v,
userid: snap.val().userid,
email: snap.val().useremail
});
})
Or, using async/await:
async function someFunction () {
const v = await this.eventData.getUserName(snap.val().userid);
rawList98.unshift({
id: snap.key,
username: v,
userid: snap.val().userid,
email: snap.val().useremail
});
}

The username property that you're pushing into the array is a promise. So to get the actual value in there, you need to use then or await:
const user = rawList98.shift();
const username = await user.username;
console.log(username);

Thanks to Frank van Puffelen. Here was the solution to my issue: I had to put the unshift() in a variable to get the index and use that to assign the username child afterward. I use rawList98.length-user since the unshift function is adding data to the bottom, not the top.
getListofReferrers() {
// Getting list of referrers from Firebase.
this.eventData.getReferrersList().on('value', snapshot => {
let rawList98 = [];
snapshot.forEach(snap => {
var user
user = rawList98.unshift({
id: snap.key,
username: null,
userid: snap.val().userid,
email: snap.val().useremail,
referralPoints: this.eventData.numberWithCommas(this.eventData.getOtherProfileProperty(snap.val().userid, "referralPoints") || 0),
});
this.eventData.getOtherNameExternal(snap.val().userid).then( (v)=> { rawList98[rawList98.length-user].username = v})
})
// Taking the information into a "this." variable
this.referralList = rawList98;
console.log(this.referralList);
});
}

Related

How to handle the JSON object which lack of some information?

I am using React with nextJS to do web developer,I want to render a list on my web page, the list information comes from the server(I use axios get function to get the information). However some JSON objects are lack of some information like the name, address and so on. My solution is to use a If- else to handle different kind of JSON object. Here is my code:
getPatientList(currentPage).then((res: any) => {
console.log("Response in ini: " , res);
//console.log(res[0].resource.name[0].given[0]);
const data: any = [];
res.map((patient: any) => {
if ("name" in patient.resource) {
let info = {
id: patient.resource.id,
//name:"test",
name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
} else {
let info = {
id: patient.resource.id,
name: "Unknow",
//name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
}
});
Is there any more clever of efficient way to solve this problem? I am new to TS and React
Use the conditional operator instead to alternate between the possible names. You should also return directly from the .map callback instead of pushing to an outside variable.
getPatientList(currentPage).then((res) => {
const mapped = res.map(({ resource }) => ({
id: resource.id,
// want to correct the spelling below?
name: "name" in resource ? resource.name[0].given[0] : "Unknow",
birthDate: resource.birthDate,
gender: resource.gender,
}));
// do other stuff with mapped
})

mongoose schema string type is not working

I used mongoose to create a schema that contains an array field called "favoriteFoods". But when I retrieved an instance and tried to push another food to this array, it failed and says "TypeError: Cannot read property 'push' of undefined".
I looked up the type of this field, it showed "undefined" instead of "array". Why is it happening?
const personSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: Number,
favoriteFoods: [String] //set up the type as an array of string
});
const Person = mongoose.model("Person", personSchema);
new Person({ name: "Lily", age: 5, favoriteFoods: "Vanilla Cake" }).save().catch(e => {
console.log(e);
})
Person.find({ name: "Lily" }, (err, data) => {
if (err) console.log(err);
console.log(data); // it gives me the object
console.log(data.favoriteFoods); // undefined
console.log(typeof (data.favoriteFoods)); // undefined
})
It looks like you are saying favoriteFoods takes an array of strings, but you are passing it a string value NOT in an array. What's more, there is also no guarantee that your new Person is done being saved before you try to find it since the operation happens asynchronously
The problem has been solved!
I made 2 changes -
Passing an array to favoriteFoods instead of a single value (Thank you #pytth!!)
Changing Model.find() to Model.findOne() because the 1st returned an array but the 2nd one returned an object
So the final code is:
const findLily = async () => {
const lily = new Person({ name: "Lily", age: 5, favoriteFoods: ["Vanilla Cake", "Lollipop"] });
await lily.save();
const found = await Person.find({ name: "Lily" });
found.favoriteFoods.push("hamburger");
await found.save();
}
Please correct me if I made any mistakes. Thanks! :)

How to populate an array inside a map function in js and send it to the server?

This is my ObjectIds array -
obj_ids = [
"5ee71cc94be8d0180c1b63db",
"5ee71c884be8d0180c1b63d9",
"5ee71c494be8d0180c1b63d6",
"5ee71bfd4be8d0180c1b63d4"
]
I am using these objectids to serach whether they exist in the db or not and based on that I want to send the response to server.
This is the code I am trying but I dont know how to populate the array and send it to the server.
var msg = [];
obj_ids.map((ele) => {
Lead.find({ _id: ele._id }, async function (error, docs) {
if (docs.length) {
msg.push(
`Lead already exist for Lead id - ${ele._id} assgined to ${docs[0].salesPerson}`
);
} else {
msg.push(`Lead doesn't exist for Lead id: ${ele._id}`);
const newDuty = new AssignedDuty({
duty: ele._id,
salesPerson: req.body.salesPerson,
});
await newDuty.save();
}
});
});
res.json(msg);
By doing this approach I am getting an empty array. I cannot put res.json(msg) inside the loop. If it is possible by using async-await, please guide me through.
You don't need to make multiple queries to find whether given object ids exist in the database.
Using $in operator, you can make one query that will return all the documents where the _id is equal to one of the object id in the list.
const docs = await Lead.find({
_id: {
$in: [
"5ee71cc94be8d0180c1b63db",
"5ee71c884be8d0180c1b63d9",
"5ee71c494be8d0180c1b63d6",
"5ee71bfd4be8d0180c1b63d4"
]
}
});
After this query, you can check which object id is present in the docs array and which is absent.
For details on $in operator, see $in comparison operator
Your code can be simplified as shown below:
const obj_ids = [
"5ee71cc94be8d0180c1b63db",
"5ee71c884be8d0180c1b63d9",
"5ee71c494be8d0180c1b63d6",
"5ee71bfd4be8d0180c1b63d4"
];
const docs = await Lead.find({
_id: { $in: obj_ids }
});
const msg = [];
obj_ids.forEach(async (id) => {
const doc = docs.find(d => d._id == id);
if (doc) {
msg.push(
`Lead already exist for Lead id - ${doc._id} assgined to ${doc.salesPerson}`
);
}
else {
msg.push(`Lead doesn't exist for Lead id: ${id}`);
const newDuty = new AssignedDuty({
duty: id,
salesPerson: req.body.salesPerson
});
await newDuty.save();
}
});
res.json(msg);

Replacing key value in array of objects

I'm working on a project that is a basic message app. basically i have created an array of objects that allows me to see pre built messages. Then i should be able to click a clear all button and clear all of the messages that are being displayed by looping through the array of objects. this is what i have so far in my messageData.js
const messages = [
{
id: 'message1',
message: 'Hello everyone! Welcome to hell',
userId: 'user1',
},
{
id: 'message2',
message: 'Yall are weirdos!',
userId: 'user3',
},
{
id: 'message3',
message: 'Hey! I think everyone is awesome!',
userId: 'user2',
},
{
id: 'message4',
message: 'Thanks for saying that my friend.',
userId: 'user4',
},
{
id: 'message5',
message: 'Hey buddy, what is up?',
userId: 'user4',
},
];
const getMessages = () => messages;
and what i want to do is basically on click allow the messages key value to be changed to an empty string onclick so that i get rid of the displayed messages without getting rid of the object so that i can later push new messages into these key values.
I started to write this but i seem to be missing something..
const clearBtnFunction = () => {
messages.splice(1, '');
};
i'll be calling the event listener on my main.js file so i'm not super worried about that part yet. I just want to know the proper syntax for replacing the key value in the array if thats possible.
Here is what i opted for. I placed this function, not in the messagesData.js but in the messages.js where i'm building the domstring
const clearBtnFunction = (e) => {
e.preventDefault();
const messages = message.getMessages();
messages.splice(0, messages.length);
messageBuilder(messages);
};
const clearBtnFunction = () => {
messages.foreach( ( message ) => {
message.message = "";
});
};
or with a for loop
const clearBtnFunction = () => {
for( let i =0; i < messages.length; i++) {
messages[i].message = "";
}
};

Pushing responses of axios request into array

I have been pounding my head against this problem, and need help with a solution. I have an array of IDs within a JSON, and I am iterating over that array and making a GET request of each ID. I want to then push the response of those GET requests into an array.
Here is the function I am using to push the registrations into the array. It is iterating through an array of IDs:
getRegistrations = async (event) => {
let registrations = [];
await event.registrations.forEach(registration => axios.get('/event/getRegistration', {
params: {
id: registration
}
}).then(res => {
registrations.push(res.data.properties)
}
).catch(err => console.log(err)));
return registrations;
};
Here is where I am calling that code:
render() {
let event = this.getEvent();
let registrations2 = [{
age: 19,
bio: 'test',
firstName: 'hello',
lastName: 'bye',
password: 'adadas',
telephone: "4920210213"
}];
if (this.props.listOfEvents.events.length !== 0 && !this.props.listOfEvents.gettingList && event) { //check if the array is empty and list has not been rendered yet
let columns = [];
let registrations = this.getRegistrations(event);
console.log(registrations);
let eventProperties = event.properties[0];
Object.keys(eventProperties).forEach(key => columns.push({
title: eventProperties[key].title,
dataIndex: key,
key: key
}));
console.log(registrations);
console.log(registrations2);
return (
<h1>hi</h1>
)
}
return <Loading/>
}
When I console-log 'registrations' vs 'registrations2' they should be very identical. However, in the javascript console on Google Chrome, 'registrations appears as '[]' where 'registrations2' appears as '[{...}]'.
I know that it is an issue related to promises (I am returning the registrations array before actually pushing) but I have no idea how to fix it! Some friendly help would be very much appreciated!
I recommend Promise.all, it will resolve single Promise after all promises have resolved. And technically async function is also promise so it will return promise.
here the example.
https://codesandbox.io/s/jzz1ko5l73?fontsize=14
You need to use componentDidMount()lifecycle method for proper execution and state to store the data.
constructor (props) {
super(props);
this.state = {registrations :[]}
}
componentDidMount () {
let response = this.getRegistrations()
this.setState({registrations : response});
}
Then access that state in render method. It's not good practice to call api from render mothod.
Since getRegistrations(event) returns a promise, you should perform operations on its return value inside then.
Instead of
let registrations = this.getRegistrations(event);
console.log(registrations);
Do this
this.getRegistrations(event).then(registrations => {
console.log(registrations);
// other operations on registrations
});

Categories