1

There is a request to Firebase, using then I add new elements to the array. If you output console.log, then there are elements, but lenght = 0 and loops do not work.

export const useLastMessageDialogs = (messagesStatus: StatusDialogType): UserMessageType[] => {
  const messages: string[] = [];

  useEffect(() => {
    const querySideDialogs = query(
      collection(firestoreDb, 'questions'),
      where('status', '==', messagesStatus)
    );

    onSnapshot(querySideDialogs, (dialogs) => {
      dialogs.docChanges().forEach((dialog) => {
        getDocs(
          query(
            collection(firestoreDb, 'questions', dialog.doc.id, 'messages'),
            orderBy('timestamp', 'desc'),
            limit(1)
          )
        ).then((response) => {
          response.forEach((message) => {
            messages.push('bebebe');
          });
        });
      });
    });
  }, [messagesStatus]);

  console.log(messages); // [0: "bebebe", 1: "bebebe" length: 2]
  console.log(messages.length); // 0

  return [];
};
Krilpil
  • 105
  • 1
  • 7
  • 1
    You are not waiting for the response to actually arrive, you already output the array just after you started the request, before it finished. So the array is empty at that point. The reason why you do see elements is because you probably clicked the expand arrow after it was already filled, and due to lazy expansion, it will then show the contents at that point in time, but I bet that the collapsed view was `[]` (empty array). (But, additionally, you don't even wait for `onSnapshot` to trigger.) – CherryDT Sep 02 '22 at 09:19
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – CherryDT Sep 02 '22 at 09:20
  • You should use ueState hook. const [messages, setMessages] = useState([]) and return messages from useLastMessageDialogs . – Angel Zlatanov Sep 02 '22 at 09:22
  • @AngelZlatanov Yes, but the component will be redrawn several times, due to the operation of the loop – Krilpil Sep 02 '22 at 09:27

1 Answers1

0

I took it to a separate service and connected it via redux-saga

Krilpil
  • 105
  • 1
  • 7