'Firebase .get() vs .once() - What is the difference?
Documentation here but I don't understand: What is the difference between .get() and .once()?
My understanding is that .get() reads from the server, and then from the local storage, and .once() reads only from the local storage. I have used.once() to retrieve values without setting up a listener like .on() and it seems to be retrieving values from the server (realtime database) that I haven't retrieved before so I'm not sure what it means when it says it only searches the local storage... It seems like it is in fact getting values from the server.
Please clarify when to use one vs the other.
I have not used .get() at all.
Solution 1:[1]
firebaser here
In practice, in the web SDK, there is no practical difference between get() and once('value', since the web SDK for Realtime Database. does not support disk persistence.
We mostly decided to add the get() method to the JavaScript SDK, as we were adding similar methods to the iOS and Android SDKs, where there is a real, but subtle, difference between the methods. For a longer explanation of that, see What is the difference between get() and addListenerForSingleValueEvent? (addListenerForSingleValueEvent is the Android variant of JavaScript's once() call).
Solution 2:[2]
.get() will always try to make a call to the database, IF only when if it is not able to reach the database or similar, it will fall back to the local cache.
on the other hand;
.once() will always try to get the value from the local cache, instead of making the call to the database, making it cost effective.
You can also look at the reference on the method which makes it more clear:
.get()
Gets the most up-to-date result for this query.
Returns Promise<DataSnapshot>
A promise which resolves to the resulting DataSnapshot if a value is available,
or rejects if the client is unable to return a value
(e.g., if the server is unreachable and there is nothing cached).
.once()
Listens for exactly one event of the specified event type,
and then stops listening.
This is equivalent to calling on(), and then calling off() inside
the callback function.
I hope this clarifies.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
| Solution 2 |
