'Firestore & React: Update the Same State in Multiple Firestore onSnapshot Listeners

We are building a chat app using Firestore and React. Users should be able to up/down-vote each other's messages. We have two Firestore collections:

  • messages: contains the message, sender, dateTime, totalVotes, ....
  • votes: contains the userVote, voter, messageId, dateTime, ....

Our React state messages is an array including all the messages to show in the UI. Each of its elements is an object with the content of the message, sender, dateTime, and totalVotes, in addition to userVote, i.e., the vote cast by the authenticated user for this message.

const [messages, setMessages] = React.useState([
  {
    message,
    sender,
    dateTime,
    totalVotes,
    userVote
  },
  ...
]);

We have two firestore.onSnapshots that listen to all the changes in messages and votes collections. This way, as soon as a message is added/updated or the user cast or change their vote for a message, the corresponding change is show in the UI.

We defined these listeners in a useEffect with no dependencies. Every time something changes in messages or votes, inside firestore.onSnapshot we call setMessages and get its previous value to update accordingly. However, when a user votes for a message, because simultaneously:

  • The message document changes it totalVotes
  • The vote document changes its values

both firestore.onSnapshots get fired, but only one of the two setMessages calls works fine. The other one messes up.

How should we solve this issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source