Firebase request: why is child_added called before requesting a value in the following code?

I have a diagram in Firebase that looks like this:

messages/
  $groupId/
    $messageId/
      message: 'Sample Message'
      createdBy: 'userID'
      createdAt: 1513337977055

Then, in my code, the following queries are executed sequentially:

// Get a specific message
ref.child('messages/$groupId/$messageId')
  .once('value')
  .then(snap => console.log('value', snap.val()))

// Start new message listener
ref.child('messages/$groupId')
  .orderByKey()
  .limitToLast(1)
  .on('child_added', snap => console.log('child_added', snap.val()))

I am wondering why it child_addedis called twice here, the first of which is similar to the value returned by the request once('value').

The console is displayed here:

child_added { message: 'Hello', createdAt: 1513337977055, createdBy: 'userId' }
value { message: 'Hello', createdAt: 1513337977055, createdBy: 'userId' }
child_added { message: 'Another message', createdAt: 1513337977066, createdBy: 'userId2' }

Please note that I am not adding new entries to Firebase here. Just a request.

EDIT: here is the link to the fiddle demonstrating the problem: https://jsfiddle.net/dspLwvc3/2/

+4
source share
1 answer

firebase here

. , , , , . , , .: -/

, , , Firebase , , .

, :

    Client                  Server
      |                       |
   (1)|  --once('value'---->  |
      |                       |
   (2)|  -on('child_added'->  |
      |                       |
      |           .           |
      |           .           |
      |           .           |
      |                       |
      |         value         |
   (3)|  <------------------- |
      |                       |
      |         child         |
   (4)|  <------------------- |
      |                       |

4 :

  • once('value') /messages/message1. .
  • on(-child_added /messages. .

  • . . once('value , . /messages/message1 /messages, child_added .

  • /messages/message3 . , , . , child_removed, /messages/message1 .

, . . , , API -. child_added once('value':

ref.child('messages/$groupId/$messageId')
  .once('value')
  .then(snap => {
    console.log('value', snap.val()))

  // Start new message listener
  ref.child('messages/$groupId')
    .orderByKey()
    .limitToLast(1)
    .on('child_added', snap => console.log('child_added', snap.val()))
  })

, child_added /messages/message1 .

Update (2018-01-07): . , ( ) . . : Firebase

+4

Source: https://habr.com/ru/post/1691164/


All Articles