i have been searching for solution for 2 days now
here is my code
saveData = () =>{
let servertime = Firebase.database.ServerValue.TIMESTAMP;
this.itemsRef.push({name:this.state.text,date:servertime});
var s = new Date(parseInt(servertime)).toUTCString();
alert(s);
}
but alert return me with invalid value
i try to put an unix interger directly like this
saveData = () =>{
let servertime = Firebase.database.ServerValue.TIMESTAMP;
this.itemsRef.push({name:this.state.text,date:servertime});
var s = new Date(1509004701954).toUTCString();
alert(s);
}
and it work well
why cant i get the same result?
Firebase.database.ServerValue.TIMESTAMP is a constant that represents the object { ".sv": "timestamp" }. Firebase uses it to automatically put in the current timestamp.
You need to push the data, then grab the snapshot and read the 'date' back:
saveData = () => {
this.itemsRef.push(
{
name:this.state.text,
date:Firebase.database.ServerValue.TIMESTAMP
}).then((snapshot) => {
var s = new Date(parseInt(snapshot.val().date)).toUTCString();
alert(s);
}
}
Related
I am developing an application with React-native and I am using firebase in the backend. the problem is that I am not able to recover the elements of my Realtime database in order of arriving. each time I launch my application the order of loading data is always different. I have thought of implementing the sorted quick to try to sort the object array received from firebase before display in my app but I received this error code: '' TypeError: undefined is not an object (evaluating 'array.length') ''. here is the code recovery of firebase objects
`import database from
'# react-native-firebase / database';
export const getAllPublications = async () => {
let list = [];
await database ()
.ref ('/ publications')
.once ('value')
.then (snapshot => {
for (const pub in snapshot.val ()) {
if (snapshot.val (). hasOwnProperty (pub)) {
const element = snapshot.val () [pub];
if (element) {
list.push ({id: pub, ... element});
}
}
}
});
return list;
} `
here my function to try to sort the table received from firebase
`export const quickSort = (array) => {
if (array.length <2) {
return array;
}
var pivot = array [0];
var lesserArray = [];
var greaterArray = [];
var date1 = new Date (pivot.timeago);
for (var i = 1; i <array.length; i ++) {
var date2 = new Date (array [i] .timeago);
if (date2.getTime ()> = date1.getTime ()) {
greaterArray.push (array [i]);
} else {
lesserArray.push (array [i]);
}
}
return quicksort (greaterArray) .concat (pivot, quicksort (lesserArray));
} `
after having received the elements of the base here is how I tried to sort them before having the error:TypeError: undefined is not an object (evaluating 'array.length')
const [publications, setPublications] = useState([]);
useEffect(() => {
getAllPublications()
.then((pubs) => {
setPublications(pubs);
setPublications(quicksort(publications));
setLoading(false);
})
}
here is an image of how my database is structured :
click here to see image
If transforming objects to arrays is something you do often when querying Firebase, you can make a short util function.
So you could do something like:
const transformFirebaseSnapshot = snapshot =>
Object.entries(snapshot.val())
.map(([id, fields]) => ({ id, ...fields }));
And use it as follows:
const getAllPublications = () => database()
.ref('/publications')
.once('value')
.then(transformFirebaseSnapshot);
Finally, put the pieces together:
const [publications, setPublications] = useState([]);
useEffect(() => {
getAllPublications()
.then(pubs => {
setPublications(quicksort(pubs));
setLoading(false);
});
}, []);
Give that a try and see if anything changes.
Good luck ;)
can you help me? I have a problem to my code coz instead of updating my map value the path changes also
const userId = firebase.auth().currentUser.uid;
const availableRecord = firebase.firestore().collection('orders').doc(this.state.OrderId);
availableRecord.update({
stores: { userId: 'On the way'}
}).then(( res) => {
console.log('Product is set into AVAILABLE')
})
Instead of
the result is
Using the square brackets notation, as follows, should do the trick:
const userId = firebase.auth().currentUser.uid;
const availableRecord = firebase.firestore().collection('orders').doc(this.state.OrderId);
const stores = {};
stores[userId] = 'On the way';
availableRecord.update({ stores }).then(() => {
console.log('Product is set into AVAILABLE');
});
Doing
availableRecord
.update({ stores: { [userId]: 'On the way' } })
also works, as you noted in your comment.
I have an app that loads some tricks. In the first iteration (next, next, play) the subscription works properly. In the second iteration (end, next, next, play) it doesn't load the tricks anymore.
The Observable is correct, it is from firebase that the tricks don't provide.
Here is some code:
console.log('did enter');
this.startDate = Date.now();
this.params = this.paramsService.get();
console.log(this.params);
console.log(this.trickService.getTricks());
var myTricks = this.trickService.getTricks()
myTricks.subscribe(tricks =>{
console.log(tricks);
this.tricksCollection = db.collection<Trick>('tricks');
this.tricks = this.tricksCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
getTricks() {
console.log(this.tricks);
return this.tricks;
}```
Anyone got a clue, I would appreciate,
Alex
I have an index of notification ids associated with a user X. When I want to display these notifications I need to fetch them from the user X's notifications index which just contains the
a) id of the notification (nid)
b) status: "read/unread"
But I also need to go to
a) /notifcations/nid to get my notification data: text and fromUser
b) /users/fromUser to get the user data for that user
My question is about structure.
Did i structure my data properly and if so, how can I fetch all this information inside the Notification and when ready, present it to angular for displaying on the screen.
Here is my take on that below. Any critique (code/structure/anything) is welcome. Thanks.
P.S.
Also if I am replacing POJOs in firebaseArray with instances of Notification, how would that affect my DB when I say edit the notification and save it back to Firebase. How does AngularFire know what to save back?
/* Notifications */
.factory('Notifications', function(firebaseUrl, NotificationsFactory){
var ref = new Firebase(firebaseUrl);
return {
getNotificationsForUser : function(uid){
var userNotifRef = ref.child('users').child(uid).child('notifications');
return new NotificationsFactory(userNotifRef);
}
}
})
.factory('NotificationsFactory', function($firebaseArray, Notification) {
return $firebaseArray.extend({
$$added : function(snapshot, prevChild){ //called anytime a 'child_added' event occurs
return new Notification(snapshot);
}
})
})
.factory('Notification', function(firebaseUrl, $q, Users) {
var notifRef = (new Firebase(firebaseUrl)).child('notifications');
var usersRef = (new Firebase(firebaseUrl)).child('users');
var mainDeferred = $q.defer();
var notifDeferred = $q.defer();
var userDeferred = $q.defer();
var Notification = function(snapshot){
this.$id = snapshot.key();
this.status = snapshot.val().status;
this.message = null;
this.from = null;
this.to = null;
notifRef.child(this.$id).once('value', function(snap){ //change to on if expect notification to keep updating
var data = snap.val();
this.message = data.message;
this.from = data.from; //user id
this.to = data.to; //user id
notifDeferred.resolve();
});
notifDeferred.promise.then(function(){
this.from = Users.getUser(this.from);
this.to = Users.getUser(this.to);
this.from.$loaded().then(function(){
this.to.$loaded().then(function(){
mainDeferred.resolve();
})
})
})
};
Notification.prototype.ready = function(){
return mainDeferred.promise;
}
return Notification;
})
I implemented a function where I want to return an object saved under a certain url. In the code below, the first 'console.log(result);' returns the right object from the firebase location. The second one return undefined. Can somebody explain why and how to fix it?
_getById: function(obj) {
var url = "https://my-app.firebaseio.com/list/" + obj.groupId;
console.log(url);
var ref = new Firebase(url);
var result = {};
ref.on("value", function(snapshot) {
result = snapshot.val(); //first
console.log(result);
}, function (errorObject) {
}
);
console.log(result); //second
return result;
},
The data is loaded from Firebase asynchronously. So you'll notice that your second console.log() displays before the first one. You cannot return data that is being loaded asynchronously.
You'll have to change the way you code. Instead of "get the id, then do something with it", you need to "do something whenever the id is loaded/changed".
So instead of:
var list = _getById({ groupId: 42});
console.log("Our list is: "+list);
You'll:
_getById({ groupId: 42 }, function(list) {
console.log("Our list is: "+list);
});
_getById: function(obj, callback) {
var url = "https://my-app.firebaseio.com/list/" + obj.groupId;
console.log(url);
var ref = new Firebase(url);
var result = {};
ref.on("value", function(snapshot) {
result = snapshot.val(); //first
callback(result);
}, function (errorObject) {
});
console.log(result); //second
return result;
},
In the above code we're passing a callback into _getById() and invoke that callback when the list has loaded (and whenever the list changes).
Some further reading material:
Polymer Firebase: Print async data
Asynchronous access to an array in Firebase
Trying to get child records from Firebase
Handling Asynchronous Calls (Firebase) in functions