I have fetched some data from firebase like so:
getUserData = () => {
database
.ref('orders/')
.once('value')
.then(function(snapshot) {
const exists = snapshot.val() !== null;
if (exists) {
let data = snapshot.val();
console.log("DATA IS: ", data);
}
});
}
The image shows the console log. I am trying to render everything on a table in react. I'm having trouble iterating through the data. Do I need to convert it into an array first?
I am looking to render everything from the item_id, displayName, email, all order info
First You need to convert into array and then you can use map for retrieve data.
For example:
if data is in array form then you can mapping of objects.
I hope it will helps you.
data.map((detail)=>{
console.log(detail.email);
})
You can get data from function,
function getUserData = () => {
database
.ref('orders/')
.once('value')
.then(function(snapshot) {
const exists = snapshot.val() !== null;
if (exists) {
let data = snapshot.val();
//console.log("DATA IS: ", data);
return data;
}
});
}
var data = getUserData();
data.forEach(function(item){
console.log(data.email);
console.log(data.img);
console.log(data.name);
console.log(data.section);
} )
New javascript provide Object.values().SO, you convert your data into array like below and use it.
getUserData = () => {
database
.ref('orders/')
.once('value')
.then(function(snapshot) {
const exists = snapshot.val() !== null;
if (exists) {
let data = snapshot.val();
console.log("DATA IS: ", data);
//use Object.values(data)
const dataArray = Object.values(data);
//now you can map your dataArray
}
});
}
Related
I have been trying to get amount of users that have same "referralId" in my firebase Realtime database,
users {
AY35bkc5cbkufik8gfe3vjbmgr {
email: james #gmail.com
verify: none
referralid: AY35ja35
}
B16fty9jDchfNgdx7Fxnjc5nxf5v {
email: mobilewisdom #gmail.com
verify: none
referralid: AY35ja35
}
}
How can I use JavaScript to count the amount of account with referralid:AY35ja35
I tried:
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
But am getting this error in my console:
Uncaught TypeError: query.get is not a function
In v8/namespaced syntax that'd be:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
const results = await query.get();
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
In v9/modular syntax the equivalent would be:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
const results = await get(query);
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
get(query).then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
Firstly you will have to run a query to get the data from firebase using either firebase package, axios or fetch
Your data is fetched in form of Object containing different objects. You can either user for .. in .. loop to iterate through the object.
var count = 0
for (const user in users) {
if (user.referralid==="AY35ja35") {
count++
}
}
Or use Object.values(object) function to get array of users. Now you can use a JavaScript array function such as map or filter.
by using map. you can do it like this:
var count=0
user.map(user=>{if(user.referralid==="AY35ja35"){count++})
or by using filter
const matchedUsers = user.filter(user=>(user.referralid==="AY35ja35"))
const count = matchedUsers.length
Hope this helps :)
I try to get specific documents from MongoDB with Node.js and insert them into array.
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
comments.forEach(async (commentId) => {
const comm = await commentModel.findOne({ _id: commentId });
data.push(comm);
console.log(data); // This returns the data in loops, because its inside a loop.
});
console.log(data); // This not returns the data and i don't know why.
return data;
};
The first console.log(data) returns the same data a lot of times because its inside a loop.
But the second console.log(data) dosen't returns the data at all.
What I'm doing wrong?
Instead of using loop , you can use $in operator to simplify things .
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
commentModel.find({ _id: { $in: comments } }, (err, comments) => {
data = comments;
});
console.log(data);
return data;
};
The getURL() function creates an array of scraped URLs from the original URL. getSubURL() then loops through that array and scrapes all of those pages' URLs. Currently, this code outputs just fine to the console, but I don't know how to wait for my data to resolve so I can push all gathered data to a single array. Currently, when I try and return sites and then push to array, it only pushes the last value. I believe it's a promise.all(map) situation, but I don't know how to write one correctly without getting an error. Ideally, my completed scrape could be called in another function. Please take a look if you can
const cheerio = require('cheerio');
const axios = require('axios');
let URL = 'https://toscrape.com';
const getURLS = async () => {
try {
const res = await axios.get(URL);
const data = res.data;
const $ = cheerio.load(data);
const urlQueue = [];
$("a[href^='http']").each((i, elem) => {
const link = $(elem).attr('href');
if (urlQueue.indexOf(link) === -1) {
urlQueue.push(link);
}
});
return urlQueue;
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
const getSubURLs = async () => {
let urls = await getURLS();
try {
//loop through each url in array
for (const url of urls) {
//fetch all html from the current url
const res = await axios.get(url);
const data = res.data;
const $ = cheerio.load(data);
//create object and push that url into that object
let sites = {};
sites.url = url;
let links = [];
//scrape all links and save in links array
$("a[href^='/']").each((i, elem) => {
const link = $(elem).attr('href');
if (links.indexOf(link) === -1) {
links.push(link);
}
//save scraped data in object
sites.links = links;
});
// returns list of {url:'url', links:[link1,link2,link3]}
console.log(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
Don't think this is a Promise related issue at heart.
You'll need to collect your sites into an array that is initialized outside the loop. Then when getSubURLs() resolves, it will resolve to your array:
const getSubURLs = async() => {
let urls = await getURLS();
let siteList = [];
try {
for (const url of urls) {
// :
// :
// :
siteList.push(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
return siteList; // array of objects
};
getSubURLs().then(console.log);
i am working on a simple app that will fetch data from an Api and display it.
a have this function
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
return fetch(api)
.then(response => response.json())
.then(response => displayUserPhotoAndName(response))
notify(`requesting profile data ...`);
};
this is where i try to fetch the data and pass as a parameter to the displayUserPhotoAndName function.
Now in the displayUserPhotoAndName function i try to create a statement that de-structures the data parameter and obtains the results property from it;
i tried to Create a second statement in the next line that de-structures the results variable i just created, and obtain the first item from it (it is an Array! See https://randomuser.me/api/). the de-structured array item should be declared as profile. This represents the profile data for the user gotten from the API call that i want to display in my app.
this is the displayUserPhotoAndName function
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
const {results} = data;
const {profile} = results;
document.getElementById('name').innerHTML = profile[results];
clearNotice();
};
now i am trying to display the title, first name and last name with this line of code document.getElementById('name').innerHTML = profile[0].title + profile[0].first + profile[0].last;.
this is not working when i try to run it in sapio
There is no profile property in data or in the results array. So your assignment const {profile} = results; will be undefined
You could point profile at the first item in the results array. Then use the property paths for what you want to display
const displayUserPhotoAndName = (data) => {
if (!data) return;
// add your code here
const {results} = data;
const profile = results[0];
const fullName = profile.name.first + ' ' + profile.name.last;
document.getElementById('name').innerHTML = fullName
};
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
return fetch(api)
.then(response => response.json())
.then(displayUserPhotoAndName)
};
getAUserProfile()
<div id="name"></div>
You need this probably:
document.getElementById('name').innerHTML = results[0].name.title + results[0].name.first + results[0].name.last;
Because the json looks like this:
{
"results":[
{
"gender":"male",
"name":{
"title":"mr",
"first":"vidar",
"last":"sjursen"
},
"location":{
"street":"bestum tverrvei 7385",
"city":"bratsberg",
"state":"sogn og fjordane",
"postcode":"8514",
"coordinates":{
"latitude":"57.7278",
"longitude":"-95.6342"
},
"timezone":{
"offset":"+7:00",
"description":"Bangkok, Hanoi, Jakarta"
}
},
"email":"vidar.sjursen#example.com",
"login":{
"uuid":"fbc411b4-f34c-497f-acff-8294ddcf8738",
"username":"whitezebra569",
"password":"shoes",
"salt":"8prWID0j",
"md5":"02ea3e887aaa140ad312905801ae2353",
"sha1":"c9a66349e68825dc02c74618aac8572fbdd01e5b",
"sha256":"8297cc85be1127223761fb80b8f554632a6a37c35d58d435293a8f6b2dca19f3"
},
"dob":{
"date":"1952-10-19T01:20:59Z",
"age":66
},
"registered":{
"date":"2011-11-12T03:06:29Z",
"age":7
},
"phone":"88795425",
"cell":"92914506",
"id":{
"name":"FN",
"value":"19105218888"
},
"picture":{
"large":"https://randomuser.me/api/portraits/men/25.jpg",
"medium":"https://randomuser.me/api/portraits/med/men/25.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/men/25.jpg"
},
"nat":"NO"
}
],
"info":{
"seed":"48917bf154395ac4",
"results":1,
"page":1,
"version":"1.2"
}
}
Which means, when you do this:
const {results} = data;
Then the array will be there, and the array doesn't have profile property to get it with:
const {profile} = results;
The problem is with this line of code
const {results} = data;
--> const {profile} = results;
the "{results}" will take the results property out of your response which in turn is an array.
when you try to take {profile} from results there is no such property like profile in it.
Which makes the profile variable undefined. This was the problem.
Note: The {something} variable will look for property in your object. [this case the property is something]
Hope this one helps
this is what worked for me
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
const {results} = data;
const [profile] = [...results];
const fullName = profile.name.title + ' ' + profile.name.last + ' ' + profile.name.first;
document.getElementById('name').innerHTML = fullName
document.getElementById('photo').src = profile.picture.large
displayExtraUserInfo(profile);
clearNotice();
};
const {profile} = results; here profile is undefined because results is an array with no property profile.
You need to do const profile = [...results]; and then document.getElementById('name').innerHTML = profile[0].name.title + profile[0].name.first + profile[0].name.last;
fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(data => {
if (!data) return;
const {
results
} = data;
const profile = [...results];
console.log(profile)
document.getElementById('name').innerHTML = profile[0].name.title + profile[0].name.first + profile[0].name.last;
}
)
<div id="name"></div>
I'm new to react native and I'm working on firebase push notification. I'm getting the notification, but the problem is I'm not able to fetch data and display it in flatlist. Notification are shown perfectly. But the problem is why I can't fetch data. I want this event data to be fteched in my notification list which i have added below image.
componentWillMount() {
const firebase = require("firebase");
if (!firebase.apps.length) {
firebase.initializeApp(db);
}
this.fetchEventsList()
}
// Fetch events list
fetchEventsList = () => {
Preference.set('userPhoneCheck', '+917508060520');
let phone = Preference.get('userPhoneCheck');
firebase.database().ref('/users').child(phone).child('/events').once('value').then((snapshot) => {
let data = snapshot.val();
let items = Object.values(data);
this.setState({
userEventsList: items
});
// this.deleteOldEvents();
this.initAllEventList();
}).then((data) => {}).catch((error) => {
//error callback
console.log('error ', error)
})
}
//fetch the friends list according to group name
initAllEventList = () => {
//let groupName='G1';
let eventId = '';
let userEventsList = [...this.state.userEventsList];
for (var i = 0; i < userEventsList.length; i++) {
eventId = userEventsList[i].eventId;
ToastAndroid.show("eventId>" + eventId, ToastAndroid.SHORT);
if (eventId != '') {
this.fetchFriendsList(eventId);
}
}
}
//app users remove that not in contacts
fetchFriendsList = (eventId) => {
let allEventsList = [...this.state.allEventsList];
firebase.database().ref('/events').child(eventId).once('value').then((snapshot) => {
let data = snapshot.val();
let items = Object.values(data);
allEventsList.push(items);
this.setState({
allEventsList: allEventsList
});
ToastAndroid.show("kk>" + allEventsList.length, ToastAndroid.SHORT);
}).then((data) => {
}).catch((error) => {
//error callback
console.log('error ', error)
})
}