Firebase endAt () в стиле фанк поведение с orderByChild () при подкачке / бесконечной прокрутке - PullRequest
0 голосов
/ 08 февраля 2019

Сначала я пытаюсь загрузить самые последние сообщения пользователя и отсортировать их в порядке убывания, но у меня возникают проблемы при использовании endAt().limitToLast() с orderByChild().

. Я могу корректно просмотреть страницы с помощью startAt().limitToFirst() сorderByChild() но мне нужно, чтобы мой список загружался с конца ... При выполнении моего запроса с использованием endAt() orderByChild (), похоже, игнорируется.

Вот мой JSON для узла categories

{
  "-LY8EYaWHINB1khsIEvJ" : {
    "Recipies" : true,
    "username" : "User1"
  },
  "-LYDaIrnDKIWndMcLE-g" : {
    "Recipies" : true,
    "username" : "User4"
  },
  "-LY8Em4B6COFk3how5FC" : {
    "Buds" : true,
    "username" : "User2"
  },
  "-LY8Eq2E1muFcOBstODa" : {...},
  "-LY8Esi98QdhszIgvRRN" : {...},
  "-LY9OSc7u8wTNQaJ7BXL" : {...},
  "-LY8EymPGxK8Y_YnRfC0" : {...},
  "-LY8F0RrYbLNPpYwIuMX" : {...},
  "-LY8F3QfERAhOq3iW3jC" : {...},
}

Вот как выглядит мой запрос (обратите внимание, мне нужно получить его снизу вверх):

  const fetchCategoryImages = (category, currentImages, lastKey) => {
      if (!lastKey) {
        return () => {
          firebase.database().ref('/categories')
            .orderByChild('Recipies' //this is the category)
            .endAt(true)
            .limitToLast(4)
            .on('value', snapshot => {
              const arrayOfKeys = Object.keys(snapshot.val())
                 .sort()
                 .reverse();

              const results = arrayOfKeys
                .map((key) => snapshot.val()[key]);

              const createLastKey = arrayOfKeys[arrayOfKeys.length - 1];

              //just passing the initial data with redux here... (snapshot and lastKey...)
            });
        };
      } else {
         //subsequent fetch if there is a lastKey to reference start point
         return () => {
           firebase.database().ref('/categories')
             .orderByChild('Recipies' //this is the category)
             .endAt(true, '-LY9OSc7u8wTNQaJ7BXL' //this is the lastKey)
             .limitToLast(3)
             .on('value', snapshot => {
               const arrayOfKeys = Object.keys(snapshot.val())
                  .sort()
                  .reverse()
                  .slice(1);

               const results = arrayOfKeys
                  .map((key) => snapshot.val()[key]);

               const createLastKey = arrayOfKeys[arrayOfKeys.length - 1];
               const concatImages = _.concat(currentImages, results);

               //passing the new data with redux here... (snapshot and lasy ley...)

               }
           });
        };
     };

Все эти проблемы исчезают, когда я просто переключаю запрос на использованиеstartAt().limitToFirst() с orderByChild() вместо.

Очень ценю всю помощь, которую я могу получить в этом вопросе, ура!

Ответы [ 2 ]

0 голосов
/ 12 февраля 2019

Я только что протестировал с этим JSON:

{
  "-LY8EYaWHINB1khsIEvJ" : {
    "Recipies" : true,
    "username" : "User1"
  },
  "-LY8Em4B6COFk3how5FC" : {
    "Buds" : true,
    "username" : "User2"
  },
  "-LY8Eq2E1muFcOBstODa" : {
    "Buds" : true,
    "username" : "User3"
  },
  "-LY8Esi98QdhszIgvRRN" : {
    "Buds" : true,
    "username" : "User4"
  },
  "-LY8EymPGxK8Y_YnRfC0" : {
    "Buds" : true,
    "username" : "User5"
  },
  "-LY8F0RrYbLNPpYwIuMX" : {
    "Buds" : true,
    "username" : "User6"
  },
  "-LY8F3QfERAhOq3iW3jC" : {
    "Receipies" : true,
    "username" : "User7"
  },
  "-LY9OSc7u8wTNQaJ7BXL" : {
    "Buds" : true,
    "username" : "User8"
  },
  "-LYDaIrnDKIWndMcLE-g" : {
    "Recipies" : true,
    "username" : "User8"
  }
}

И этот код:

ref.orderByChild('Buds')
  .endAt(true, '-LY9OSc7u8wTNQaJ7BXL')
  .limitToLast(3)
  .once('value', snapshot => {
    snapshot.forEach(child => {
      console.log(child.key+": "+JSON.stringify(child.val()));
    })
  })

Живой образец: https://jsbin.com/zigofok/edit?js,console

При запуске это печатает:

"- LY8EymPGxK8Y_YnRfC0: {\" Buds \ ": true, \" username \ ": \" User5 \ "}"

"- LY8F0RrYbLNPpYwIuMX: {\" Buds \ ": true, \ "username \": \ "User6 \"} "

" - LY9OSc7u8wTNQaJ7BXL: {\ "Buds \": true, \ "username \": \ "User8 \"} "

Обратите внимание, как там пропускается User7, поскольку у этого пользователя нет свойства Buds.

0 голосов
/ 11 февраля 2019

Итак, после попытки ПОЧТИ все, оказывается, все, что мне нужно было сделать, это тоже добавить startAt(true).Я не уверен, почему, но это работает.У меня есть другие запросы, которые почти такие же, как этот, которые работают без него - лучше, чем мой ... хотелось бы знать, зачем мне это нужно для того, чтобы это работало.

вот мой рабочий код:

 const fetchCategoryImages = (category, currentImages, lastKey) => {
      if (!lastKey) {
        return () => {
          firebase.database().ref('/categories')
            .orderByChild('Recipies' //this is the category)
            //THE SOLUTION
            .startAt(true)
            .endAt(true)
            .limitToLast(4)
            .on('value', snapshot => {
          const arrayOfKeys = Object.keys(snapshot.val())
             .sort()
             .reverse();

          const results = arrayOfKeys
            .map((key) => snapshot.val()[key]);

          const createLastKey = arrayOfKeys[arrayOfKeys.length - 1];

          //just passing the initial data with redux here... (snapshot and lastKey...)
        });
    };
  } else {
     //subsequent fetch if there is a lastKey to reference start point
     return () => {
       firebase.database().ref('/categories')
         .orderByChild('Recipies' //this is the category)
          //THE SOLUTION
          .startAt(true)
         .endAt(true, '-LY9OSc7u8wTNQaJ7BXL' //this is the lastKey)
         .limitToLast(3)
         .on('value', snapshot => {
           const arrayOfKeys = Object.keys(snapshot.val())
              .sort()
              .reverse()
              .slice(1);

           const results = arrayOfKeys
              .map((key) => snapshot.val()[key]);

           const createLastKey = arrayOfKeys[arrayOfKeys.length - 1];
           const concatImages = _.concat(currentImages, results);

           //passing the new data with redux here... (snapshot and lasy ley...)

           }
       });
    };
 };
...