How to read list of data from Firebase? - javascript

I'm building simple app using Firebase just to get a sense how to work with it.
Currently, I create notes using following approach
const notes = db.ref(`users/${user.uid}/notes`).push();
notes.set({
title,
description
});
But, how do I retrieve this list of data ?
Thanks in advance.

Here's my approach based on the documentation:
const readUsersFromSnapshot = snapshot => {
const users = [];
snapshot.forEach(child => {
users.push(child.val());
});
database.ref('users').off();
return Promise.resolve(users);
};
const getUsers = () =>
database
.ref('users')
.once('value')
.then(readUsersFromSnapshot);
// getUsers().then(users => {
// users array
// });

Related

How to get nested key in firebase real time database

I am creating a database for the products. The products are pushed into the database successfully but I am facing a problem in getting the data because the keys are nested. How can I target the nested key?
Please help me.
Using the below code I am getting my all the products data of currently logged in user.
useEffect(() => {
const getProductsData = async () => {
const userId = await AsyncStorage.getItem('uid')
database()
.ref(`Products/${userId}`)
.on('value', data => {
console.log(data.val())
});
}
getProductsData()
}, [])
console of the data.val()
Assuming that your userId is the dUD7M... value in the screenshot you shared, the data snapshot you get will contain the data for both child nodes in that screenshot. You can loop over those children with:
const userId = await AsyncStorage.getItem('uid')
database()
.ref(`Products/${userId}`)
.on('value', snapshot => {
snapshot.forEach((data) => { // 👈
console.log(data.val())
});
});

Sorting data by timestamp in Firebase Realtime Database (Javascript)

I need to sort my data in Firebase Realtime Database based on their timestamp. Latest data needs to be at the very top. How can I do this using orderByChild?
This is my code when fetching the database:
function GetAllDataRealtime() {
const dbRef = ref(database, 'Users');
onValue(dbRef,(snapshot) => {
var Users = [];
snapshot.forEach(userSnapshot => {
Users.push(userSnapshot.val());
});
AddAllITemsToTable(Users);
})
}
window.onload = GetAllDataRealtime;
Hope this helps
ref.orderByChild("timestamp").on("value", (value) => { ...

Value (number) is different from the MongoDB to the react client async call

Problem:
An entire field of my MongoDB's collections' is not transmitted correctly from the db to the react client. For an exemple, the first element of this field is tweet_id: 1537466989966413825 in my DB. It becomes tweet_id: 1537466989966413800 when I fetch from my client.
My steps
I pull my data from the MongoDB using their App services' function like that:
exports = function(){
var collection = context.services.get("mongodb-atlas").db("meme_news").collection("news");
return collection.find({});
};
When I press the Run button of their built-in terminal, the correct data is displayed.
On my react's application, I perform the fetch like that:
useEffect(() => {
getData();
}, []);
const getData = async () => {
let getAllData = await user.functions.getAllData();
// all these data are wrong
let tweetId = getAllData
.map((ele) => {
return ele.tweet_id;
})
let tweetIdFirstEle = tweetId[0];
// this return 1537466989966413800
// It should return 1537466989966413825
};
Why is my async/await altering my Mongodb data? I have no idea what is going on here.

How to fetch all the documents with unique id from firestore database using React?

[Firestore SS][1]
[1]: https://i.stack.imgur.com/EI1Dm.png
I want to fetch each document as displayed in SS it's stored as Pets + unique_userId.
I am unable to fetch all data together. Just able to fetch one data of a particular user using the code below.
const [info,setInfo]=useState([]);
useEffect(() => {
db.collection("pets ESYXOPqlJpZ48np8LfNivnh9pvc2").onSnapshot((snapshot) =>
setInfo(snapshot.docs.map((doc) => doc.data()))
);
},[]);
Here ESYXOPqlJpZ48np8LfNivnh9pvc2 this is the userID of each unique user
Please help me out to fetch all the Pets data instead of hardcoding and fetching one particular data.
Try the following code,
const [docs, setDocs] = useState([]);
useEffect(() => {
const querySnapshot = await getDocs(collection(db,"pets ESYXOPqlJpZ48np8LfNivnh9pvc2"));
const document =[];
querySnapshot.forEach((doc) => {
document.push({
...doc.data(),
id: doc.id
});
});
setdocs(document);
}, []);
I'm guessing the appended id is a reference to the owner's id? In this case, would it be an option to fetch the owner list and use everyone's id to build a list of collection ids and then get all of their data?
If not, I only see to options:
Rethink your database structure - maybe use a unified pets collection and have a reference with/to that id in the pet documents.
Create a cloud function in which use #google-cloud/firestore to get the list of collections. There are tons of resources out there to help you get started with firebase cloud functions. Their documentation is pretty good also, and probably the most up-to-date
const functions = require('firebase-functions')
const { Firestore } = require('#google-cloud/firestore');
module.exports = functions
.region('europe-west3') // use the region you want here
.https.onRequest(async (request, response) => {
try {
const firestore = new Firestore();
const collections = (await firestore.listCollections()).map(collection => collection.id)
response.json({ data: collections })
} catch (error) {
response.status(500).send(error.message)
}
})
You'll get and endpoint which you can use to fetch the collection ids (e.g.: https://your-project-name.cloudfunctions.net/collections)
const [pets, setPets] = useState([]);
const [collectionIds, setCollectionIds] = useState([])
useEffect(() => {
fetch('https://your-project-name.cloudfunctions.net/collections')
.then(response => response.json())
.then(({ data }) => setCollectionIds(data))
}, [])
useEffect(() => {
collectionIds.forEach((collectionId) => {
// There are better ways to do this,
// I'm just using your approach so you can focus on the rest of the code
db.collection(collectionId).onSnapshot((snapshot) => {
setPets((currentPets) => [...currentPets, ...snapshot.docs.map((doc) => doc.data())])
})
})
}, [collectionIds])
Please note that these are very high-level implementations, there's no error handling, no teardowns or anything, so keep that in mind. Hope it helps, good luck!

Github user finder api, how to return multiple users per search? JS

Hello I am using github api to create github user finder. my question is how to manipulate on api link to get users which include e.target.value of the searchbar and not only that one that exactly matches.
here is my code
const [finalData, setFinalData] = useState([]);
const handleSearch = async (e) => {
try {
const URL = `https://api.github.com/users/${e.target.value}?
client_id=e25d1dbedde5215999ef&client_secret=ee080580b7c4f19688ccaef6844c3fe88bb811d`;
Promise.all([fetch(URL).then((res) => res.json())]).then((data) => {
if (data) {
setData(data);
}
});
} catch (err) {
console.log(err);
}
};
const setData = (data) => {
data && setFinalData(data);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
You can use the Search users endpoint. There is a query parameter (q) that allows you to use multiple search criteria documented here
Here's an example using Octokit, but if you still want to use fetch, the endpoint should be https://api.github.com/search/users
Note: I really hope the client secret you are exposing here is for a test application.
Search GitHub users                                                                                
View in Fusebit
const userSearch = ''; // Specify the search text here
const usersResponse = await octokit.rest.search.users({
q: userSearch,
per_page:100
});
const { total_count, items } = usersResponse.data;
console.log(`Listing ${items.length} users of ${total_count} \n`, items.map(user => user.login));

Categories