Retrieve data as array of objects || Firebase - javascript

Im kinda new in firebase. As a first step, I would like to set a post and get calls to my newly made database in firebase.
Firebase has a lot of native functions which allows me to get elements and push them to the db. However, I would prefer to use native get/post calls.
My post calls seem to work just fine, it properly stores an element in the db and returns 200 status.
When I enter to my DB in firebase, I can see that it posses following data:
entries:
-L1cxn3-rLgp7PsPwjV3
author: "Mark"
title: "Hello"
-L1cyaOQ4TUYd3m16VfT
autor: "Lily"
title: "Hi"
So as I said before, it stores correct data. But the structure is unknown for me. It's like a map or an object.
I would like to ask you for help, how to properly retrieve it from get call.
The get call returns:
{"-L1cxn3-rLgp7PsPwjV3":{"author":"Mark","title":"Hello"},"-L1cyaOQ4TUYd3m16VfT":{"author":"Lily","title":"Hi"}};
I could take all keys from it Object.keys(data)
Then iterate over it to get it as an array -
Object.keys(data).map(r => data[r])
Now I would have an array of objects.
Is it a proper way to deal with it? Should I stay with my get/post calls or I should rather use firebase built-in functions? Thank u in advance! :)

Just use Object.values() if you want the array of objects
console.log(Object.values({"-L1cxn3-rLgp7PsPwjV3":{"author":"Mark","title":"Hello"},"-L1cyaOQ4TUYd3m16VfT":{"author":"Lily","title":"Hi"}}))

Related

Firebase database. How to append values to array?

I have the following test data
1: {
match: "Game 1",
scorer: ["foo","bar"] //this could also be an object
}
My question is how do I correctly append new value to an array without overwriting it? My idea was to retrieve existing data then spread it like so [...currentData, "bob"]. Is there a better alternative?
const addScorer = (matchId) => {
return update(ref(db, path), {
scorer: ["bob"]
})
}
There is no atomic operation to add an item to an array directly in the database. This means you'll need to:
Read the array into your application code
Append the item to the array
Write the entire array back to the database
This is one of the many reasons why Firebase recommends against using arrays for lists of data, but instead has a push() operation that circumvents most problems. For more on this, see the link to the document that Nilesh included in their comment, or read this article on Best Practices: Arrays in Firebase.

Trying to turn an array of entries into an object but doesn't work, why?

I'm trying to turn an array in which every element is an array containing the key, and the value(like entries), I'm trying to convert it back to an object element by the help of the method Object.fromEntries(array) but there seem to be a problem.
This is the error I get: TypeError: Object.fromEntries requires the first iterable parameter yields objects
Here's how I use the method:
const saved = JSON.parse(Object.fromEntries(localStorage.getItem(key)))
The local storage value it should retrieve:
[["$$typeof",null],["type",null],["key",null],["ref",null],["props",{"data":"a data containing collections of objects(fetched from an API)"}]
Since it might be helpful, what I'm trying to do is to store a react component(yes, I work on ReactJS) to local storage and get it back when necessary.
If you don't think that this portion of code is not the reason why this issue appears, please do let me know.

Storing empty arrays in firebase

I have my firebase app working with React whereby I sign users up and then log there information to the database. I am creating a "dating app" and I would like some way to store empty arrays. e.g, matchers: [] etc
I tried something liket this:
firebase.database().ref('users/' + userId).set({
id: userId,
username: name,
email: email,
matchers: [],
likedUsers: [],
disLikedUsers: []
});
but then read that firebase doesn't really handle arrays as such and now am not sure how to do this. I want the empty array so then when the user starts using the app they can add to their various arrays.
any ideas?
Firebase has always recommended against using arrays. Instead of re-iterating the reasons, I'll point you to the blog post Best Practices: Arrays in Firebase.
But your bigger problem seems to be having empty arrays: the . If a property doesn't have a value, the Firebase Database doesn't store that property. That means that an empty array is not stored in the database and thus not read back.
You'll have to re-create those properties yourself after you read the data back. If you're having problems with this, update your question to show how you read the data.
You don't need to create those fields, they are initialized with the first item and the recommended way to indexed collections is to use the push and later to map it to an array.

Append to an arary field in Firestore

I'm using Firebase and Vuejs to create an database element, which has object array inside.
That's how the field looks, and I want to add tasks through the form into the 'moreTasks' as an array.
I tried using this, but it just creates new entity in the database.
db.collection('Tasks').add({
tasker: this.tasker.taskerName
})
I also tried checking API but I couldnt understand the refs, because I was using different methods to achieve that goal.
creatTask() {
db.collection('Tasks').add({
task_id: this.task_id,
name: this.name,
What would be correct way to approach this problem?
You can append an item to an array using FieldValue.arrayUnion() as described in the documentation. For example:
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
The accepted answer used to be correct but is now wrong. Now there is an atomic append operation using the arrayUnion method:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
This is true as long as you are using firestore and not real time db (which I assume is the case from the tags)

Storing a php array client side

I have a web page that queries a database to get a list of products with their related data like price, size,weight e.t.c and displays it to the user, I want to add one of those sort dropdown list so that a user can sort the products by price or any other key I specify.
I plan to do it using Ajax on dropdown change query the database again and use the selected value as the sort key in the query.
My question is, is there a way that this can be done client side without running another query? Can php send the query result to the browser and store it there and then use jquery to sort it over and over again?
Thanks everyone for the help!
There are many ways this can be achieved. A simple example can be done with HTML5 LocalStorage.
Here's a general overview of how that can be done:
You make an initial call to your DB for products via AJAX, returns a JSON object.
You serialize that JSON object via javascript e.g. var stringData = JSON.stringify(data)
Store said variable into localstorage: window.localStorage.setItem("products", stringData);
You can then later access it via var products = window.localStorage.getItem("products) and finally deserialize it with var productsObj = JSON.parse(products) or do it all in one c-c-c-c-c-combo breaker: productsObj = JSON.parse(window.localStorage.getItem("products))
Do as you please by using filtering functions!
Another way is to store the initial JSON object using some form of store e.g. Redux, but let's save that for another day ;)
And of course, you may optionally have a globally accessible object that you can assign the initial JSON data to as a property and later access as you would any other property.
Take a look at this jquery plugin
http://tablesorter.com/docs/example-ajax.html
Maybe it's what you are looking for? No need to requery the database.

Categories

Resources