I want to update my state adding new messages from Firestore onSnapshot to the existing array of messages but inside onSnapshot I only have access to the state when the subscription was done.
const [messages, setMessages] = useState([]);
useEffect(() => {
const ref = firestore()
.collection('Msg_Messages')
return ref.onSnapshot(querySnapshot =>
setMessages(messages => messages.concat(querySnapshot.docs)))
}, [])
When I receive a message I get:
OnMountMessages + lastMessage
instead of
OnMountMessages + allMessagesSinceMount + lastMessage
I guess becase onSnapshot creates his own copy of messages and setMessages. The only solution I can think about is to use Redux and keep the state outside of the component, but is there an other solution?